替换Curley大括号JavaScript内的文本 [英] Replacing Text Inside of Curley Braces JavaScript

查看:68
本文介绍了替换Curley大括号JavaScript内的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JavaScript动态替换花括号内的内容.这是我的代码示例:

I am trying to use JavaScript to dynamically replace content inside of curly braces. Here is an example of my code:

var myString = "This is {name}'s {adjective} {type} in JavaScript! Yes, a {type}!";
var replaceArray = ['name', 'adjective', 'type'];
var replaceWith = ['John', 'simple', 'string'];

for(var i = 0; i <= replaceArray.length - 1; i ++) {
  myString.replace(/\{replaceArray[i]\}/gi, replaceWith[i]);
}

alert(myString);

上面的代码应该输出这是John在JavaScript中的简单字符串!是的,是字符串!".

The above code, should, output "This is John's simple string in JavaScript! Yes, a string!".

这是会发生什么:

  1. 我们得到了一个字符串,其中的括号中的值需要替换
  2. 循环使用"replaceArray"在花括号中查找所有需要替换的值
  3. 这些值以及花括号将被"replaceWith"数组中的相应值替换

但是,我没有任何运气,尤其是由于一个值可能会在多个位置替换,并且我正在正则表达式内部处理动态值.

However, I am not having any luck, especially since one value may be replaced in multiple locations, and that I am dealing a dynamic value inside of the regular expression.

有人可以使用上面类似的设置来帮助我解决此问题吗?

Can anyone help me fix this, using a similar setup as above?

推荐答案

首先, String.replace 不是破坏性的-它不会更改字符串本身,因此您必须设置 myString = myString.replace(...).其次,您可以使用 new RegExp 动态创建 RegExp 对象,因此所有操作的结果将是:

First, String.replace is not destructive - it doesn't change the string itself, so you'll have to set myString = myString.replace(...). Second, you can create RegExp objects dynamically with new RegExp, so the result of all that would be:

var myString = "This is {name}'s {adjective} {type} in JavaScript! Yes, a {type}!",
    replaceArray = ['name', 'adjective', 'type'],
    replaceWith = ['John', 'simple', 'string'];

for(var i = 0; i < replaceArray.length; i++) {
    myString = myString.replace(new RegExp('{' + replaceArray[i] + '}', 'gi'), replaceWith[i]);
}

这篇关于替换Curley大括号JavaScript内的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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