我想在JavaScript中创建一个String.replaceAll()方法,我认为使用RegEx将是最简洁的方法.但是,我无法弄清楚如何将变量传递给RegEx.我已经可以做到这一点,它将用"A"替换所有"B"的实例.
"ABABAB".replace(/B/g, "A");
Run Code Online (Sandbox Code Playgroud)
但我想做这样的事情:
String.prototype.replaceAll = function(replaceThis, withThis) {
this.replace(/replaceThis/g, withThis);
};
Run Code Online (Sandbox Code Playgroud)
但显然这只会替换文本"replaceThis"...所以如何将此变量传递给我的RegEx字符串?
我只想用任何可能的字符串创建一个正则表达式.
var usersString = "Hello?!*`~World()[]";
var expression = new RegExp(RegExp.escape(usersString))
var matches = "Hello".match(expression);
Run Code Online (Sandbox Code Playgroud)
有内置的方法吗?如果没有,人们会用什么?Ruby有RegExp.escape.我觉得我不需要自己编写,那里必须有标准的东西.谢谢!
尝试用变量替换字符串中#的所有实例.它没有工作,但也没有重新调整任何错误.
answer_form = '<textarea name="answer_#" rows="5"></textarea>'+
'<input type="file" name="img_#" />';
question_num = 5;
answer_form.replace(/#/g, question_num);
Run Code Online (Sandbox Code Playgroud)
哈希仍然存在.
不确定我错过了什么?