在RegExp中发布特殊字符和字母组合

时间:2019-06-25 13:14:57

标签: javascript regex

我有一个RegExp,它用HTML格式的类替换字母:

strHTMLCode.replace( new RegExp("(" + strValue + ")", "ig"), '<word class="highlightedWord">' + strActualWord + '</word>');

但是当出现特殊字符时,它会失败。

赞: 输入:“ $”

预期输出为:"<word class="highlightedWord">$</word>110.00"

实际输出:"$110.00<word class="highlightedWord">$</word>"

我尝试添加此内容:

strValue = strValue.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&');
strHTMLCode = strHTMLCode.replace( new RegExp("(" + strValue + ")", "ig"), '<word class="highlightedWord">' + strActualWord + '</word>');

但是在浏览器控制台中,这会转换为:

strValue = strValue.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\$&');

所以我尝试添加:strValue = strValue.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\\$&');

这很好,但反之则不起作用。

代码:strHTMLCode.replace(new RegExp("(" + strConstRegex + ")", "ig"), strText);

strConstRegex = "<word class="highlightedWord">$</word>" 和strtext = '$'。 而strhtmlCode = "<word class="highlightedWord">$</word>110.00" 预期输出='$' 实际输出= "<word class="highlightedWord">$</word>110.00"

更新的代码:

var strHTMLCode = '<word class="highlightedWord">$</word>110.00'; var strConstRegex = '<word class="highlightedWord">$</word>'; var strtext = '$'; strHTMLCode.replace(new RegExp("(" + strConstRegex + ")", "ig"), strText);

0 个答案:

没有答案