Exact replace of string in Javascript -


hidvalue="javascript:java"; replacestr = "java"; resultstr=hidvalue.replace("/\b"+replacestr+"\b/gi",""); 

resultstr still contains "javascript:java"

the above code not replacing exact string java. when change code , directly pass value 'java' it's getting replaced correctly i.e

hidvalue="javascript:java"; resultstr=hidvalue.replace(/\bjava\b/gi,""); 

resultstr contains "javascript:"

so how should pass variable replace function such exact match replaced.

the replace-function not take string first argument regexp-object. may not mix 2 up. create rexexp-object out of combined string, use appropriate constructor:

resultstr=hidvalue.replace(new regexp("\\b"+replacestr+"\\b","gi"),""); 

note double backslashes: want backslash in regular expression, backslash serves escape character in string, you'll have double it.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -