用循环替换简单的 Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11446105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple Javascript replace with a loop
提问by Alex Guerin
I'm try to replace all occurances wihtin a string with the array index value as below.
我试图用数组索引值替换字符串中的所有出现,如下所示。
var str = '<a href="{0}" title="{1}">{1}</a>';
var params= [];
params.push('Url', 'TitleDisplay');
for (i in params) {
var x = /'{' + i + '}'/g;
str = str.replace(x, params[i]);
}
No matter what I do, I cannot seem to get it to work. Dropping the '/g' works with one match, but not all. I know this is basic but for the lide of me I cannot get it to work.
无论我做什么,我似乎都无法让它发挥作用。删除 '/g' 仅适用于一场比赛,但不是全部。我知道这是基本的,但对于我来说,我无法让它发挥作用。
回答by Christophe
Code:
代码:
var rx = /{([0-9]+)}/g;
str=str.replace(rx,function(var x = new RegExp("\{" + i + "\}", "g");
,){return params[];});
The replace method loops through the string (because of /g in the regex) and finds all instances of {n} where n is a number. $1 captures the number and the function replaces {n} with params[n].
replace 方法循环遍历字符串(因为正则表达式中的 /g)并找到 {n} 的所有实例,其中 n 是一个数字。$1 捕获数字,函数将 {n} 替换为 params[n]。
回答by GottZ
try using this:
尝试使用这个:
var x = /'{' + i + '}'/g;
instead of this:
而不是这个:
var str = '<a href="{0}" title="{1}">{1}</a>';
var params= [];
params.push('Url', 'TitleDisplay');
for (var i = 0; i < params.length; i++) {
var x = new RegExp('(\{'+i+'\})', 'g');
str = str.replace(x, params[i]);
}
alert(str);
?
回答by Musa
You can build a regexp object if you need it to be dynamic
如果您需要它是动态的,您可以构建一个正则表达式对象
function replaceAllOccurrences(inputString, oldStr, newStr)
{
while (inputString.indexOf(oldStr) >= 0)
{
inputString = inputString.replace(oldStr, newStr);
}
return inputString;
}
回答by Gene Bo
How about this if you would like to skip a regex solution ..
如果您想跳过正则表达式解决方案,那如何..
##代码##