以下是我的replace()
功能
SomeString.replace(/\[check\]/, "<input type='checkbox'>");
我的问题是:我可以在替换功能中使用两个搜索值吗?
例如:如果匹配/\[check\]/
,请替换为<input type='checkbox'>
,如果匹配\[check111\]
,请替换为<input type='radio'>
。
我可以将两个搜索值都写入一个.replace()
函数吗?
答案 0 :(得分:1)
是强>
您可以将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
&#13;
RegEx说明:
\[check
:匹配[check
(?:111)?
:匹配111零或一次,不要捕获它。因此111
是可选的。\]
:匹配]
文字