How to replace all occurences of a variable in a string using javascript?

穿精又带淫゛_ 提交于 2021-01-27 07:30:48

问题


I'm trying to replace all the occurrences of a variable in a string using javascript.

This is not working.:

var id = "__1";
var re = new RegExp('/' + id + '/g');
var newHtml = oldHtml.replace( re, "__2");

This is only replacing the first occurrence of id:

var id = "__1";
var newHtml = oldHtml.replace( id,"__2");

What am I doing wrong here?

Thanks


回答1:


When you instantiate the RegExp object, you don't need to use slashes; the flags are passed as a second argument. For example:

var id = "__1";
var re = new RegExp(id, 'g');
var newHtml = oldHtml.replace( re, "__2");



回答2:


You need the slashes before and after the string to replace (id).

Example



来源:https://stackoverflow.com/questions/1289330/how-to-replace-all-occurences-of-a-variable-in-a-string-using-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!