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
Post a Comment