用循环替换简单的 Javascript [英] Simple Javascript replace with a loop

查看:44
本文介绍了用循环替换简单的 Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用数组索引值替换字符串中的所有出现,如下所示.

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]);
}

无论我做什么,我似乎都无法让它发挥作用.删除 '/g' 仅适用于一场比赛,但不是全部.我知道这是基本的,但对于我来说,我无法让它工作.

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.

推荐答案

Fiddle here

代码:

var rx = /{([0-9]+)}/g;
str=str.replace(rx,function($0,$1){return params[$1];});

replace 方法遍历字符串(因为正则表达式中的/g)并找到 {n} 的所有实例,其中 n 是一个数字.$1 捕获数字,函数将 {n} 替换为 params[n].

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].

这篇关于用循环替换简单的 Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆