可以用两个搜索值替换JavaScript.replacement函数

Can JavaScript .replace function with two search value?

本文关键字:搜索 替换 JavaScript 函数 replacement 两个      更新时间:2024-03-12

下面是我的replace()函数

SomeString.replace(/'[check']/, "<input type='checkbox'>");

我的问题是:我可以在替换函数中有两个搜索值吗?

例如:如果与/'[check']/匹配,则替换为<input type='checkbox'>;如果与'[check111']匹配,则更换为<input type='radio'>

我可以将两个搜索值都写入一个.replace()函数吗?

您可以使用带有回调功能的String#replace。在回调中,使用三元运算符或if...else语句来检查匹配的内容和应该替换的内容。

someString.replace(/'[check(?:111)?']/g, function($0) {
    return "<input type='" + ($0 === '[check]' ? 'checkbox' : 'radio') + "'>";
    // $0 here is the complete string match
});

演示:

var someString = 'Hello [check], did you say [check111]?';
var result = someString.replace(/'[check(?:111)?']/g, function ($0) {
    return "<input type='" + ($0 === '[check]' ? 'checkbox' : 'radio') + "'>";
});
console.log(result);
document.body.innerHTML = result; // FOR DEMO ONLY

RegEx解释:

  1. '[check:匹配[check
  2. (?:111)?:匹配111零或一次,并且不捕获它。因此111在这里是可选的
  3. ']:匹配]文字