admin管理员组文章数量:1356914
hidValue="javaScript:java";
replaceStr = "java";
resultStr=hidValue.replace("/\b"+replaceStr+"\b/gi","");
resultStr still contains "javaScript:java"
The above code is not replacing the exact string java. But when I change the code and directly pass the value 'java' it's getting replaced correctly i.e
hidValue="javaScript:java";
resultStr=hidValue.replace(/\bjava\b/gi,"");
resultStr contains "javaScript:"
So how should I pass a variable to replace function such that only the exact match is replaced.
hidValue="javaScript:java";
replaceStr = "java";
resultStr=hidValue.replace("/\b"+replaceStr+"\b/gi","");
resultStr still contains "javaScript:java"
The above code is not replacing the exact string java. But when I change the code and directly pass the value 'java' it's getting replaced correctly i.e
hidValue="javaScript:java";
resultStr=hidValue.replace(/\bjava\b/gi,"");
resultStr contains "javaScript:"
So how should I pass a variable to replace function such that only the exact match is replaced.
Share Improve this question asked Dec 1, 2010 at 7:20 GopiGopi 5,90723 gold badges88 silver badges151 bronze badges3 Answers
Reset to default 5The replace-function does not take a string as first argument but a RegExp-object. You may not mix those two up. To create a RexExp-object out of a bined string, use the appropriate constructor:
resultStr=hidValue.replace(new RegExp("\\b"+replaceStr+"\\b","gi"),"");
Note the double backslashes: You want a backslash in your Regular Expression, but a backslash also serves as escape character in the string, so you'll have to double it.
Notice that in one case you're passing a regular expression literal /\bjava\b/gi
, and in the other you're passing a string "/\bjava\b/gi"
. When using a string as the pattern, String.replace
will look for that string, it will not treat the pattern as a regular expression.
If you need to make a regular expression using variables, do it like so:
new RegExp("\\b" + replaceStr + "\\b", "gi")
See:
https://developer.mozilla/en/JavaScript/Reference/Global_Objects/RegExp
https://developer.mozilla/en/JavaScript/Reference/Global_Objects/String/replace
`let msisdn = '5093240556699' let isdnWith = numb.msisdn.slice(8,11); let msisdnNew = msisdn.replace(isdnWith, 'XXX', 'gi');
show 5093240556XXX`
本文标签: Exact replace of string in JavascriptStack Overflow
版权声明:本文标题:Exact replace of string in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744059260a2583824.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论