我正在尝试使用 JavaScript 动态替换大括号内的内容。下面是我的代码示例:
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 中的简单字符串!是的,一个字符串!”。
发生的情况如下:
- 我们得到一个字符串,其中大括号中的值需要替换,
- 循环使用“replaceArray”来查找大括号中需要替换的所有值
- ,这些值以及大括号将被替换为“replaceWith”数组中的相应值
但是,我没有任何运气,特别是因为一个值可能在多个位置被替换,并且我正在正则表达式内部处理动态值。
任何人都可以使用与上面类似的设置来帮助我解决这个问题吗?
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);
The above code, should, output "This is John's simple string in JavaScript! Yes, a string!".
Here is what happens:
- we are given a string with values in braces that need replaced
- a loop uses "replaceArray" to find all of the values in curly braces that will need replaced
- these values, along with the curly braces, will be replaced with the corresponding values in the "replaceWith" array
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?
发布评论
评论(5)
首先,
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 setmyString = myString.replace(...)
. Second, you can createRegExp
objects dynamically withnew RegExp
, so the result of all that would be:我发现做到这一点的最好方法是使用内联替换函数,就像其他人提到的那样,以及我从谁那里借来的。特别感谢 @yannic-hamann 的正则表达式和清晰的示例。我并不担心性能,因为我这样做只是为了构建路径。
我在 MDN 文档 中找到了解决方案。
The best way I have found to do this, is to use an in-line replace function like others have mentioned, and from whom I borrowed. Special shout out to @yannic-hamann for the regex and clear example. I am not worried about performance, as I am only doing this to construct paths.
I found my solution in MDN's docs.
字符串是不可变的
JavaScript 中的字符串是不可变的。这意味着这永远不会像您期望的那样工作:
这不仅仅是
.replace()
的问题 - 没有任何东西可以改变 JavaScript 中的字符串。你可以做的是:正则表达式文字不插入值
JavaScript 中的正则表达式文字不插入值,所以这仍然不起作用:
你必须做这样的事情:
但这有点混乱,所以你可以先创建一个正则表达式列表:
如您所见,您还可以使用
i
i
i
i
i
i
i
i
i
i
i ReplaceArray.length
而不是i <= ReplaceArray.length - 1
来简化循环条件。更新 2017
现在您可以使其变得更加简单:
无需循环
您只需执行一次即可,而不是一遍又一遍地循环和应用
.replace()
函数:请参阅 演示。
模板引擎
您基本上是在创建自己的模板引擎。如果您想使用现成的解决方案,请考虑使用:
或类似的东西。
您尝试使用 Mustache 执行的操作示例如下:
请参阅 DEMO。
Strings are immutable
Strings in JavaScript are immutable. It means that this will never work as you expect:
This is not just a problem with
.replace()
- nothing can mutate a string in JavaScript. What you can do instead is:Regex literals don't interpolate values
Regular expression literals in JavaScript don't interpolate values so this will still not work:
You have to do something like this instead:
But this is a little bit messy, so you may create a list of regexes first:
As you can see, you can also use
i < replaceArray.length
instead ofi <= replaceArray.length - 1
to simplify your loop condition.Update 2017
Now you can make it even simpler:
Without a loop
Instead of looping and applying
.replace()
function over and over again, you can do it only once like this:See DEMO.
Templating engines
You are basically creating your own templating engine. If you want to use a ready solution instead, then consider using:
or something like that.
An example of what you are trying to do using Mustache would be:
See DEMO.
这是一个接受字符串和替换数组的函数。它足够灵活,可以重复使用。唯一的问题是,您需要在字符串中使用数字而不是字符串。例如,
演示:https://jsfiddle.net/4cfy7qvn/
Here's a function that takes the string and an array of replacements. It's flexible enough to be re-used. The only catch is, you need to use numbers in your string instead of strings. e.g.,
Demo: https://jsfiddle.net/4cfy7qvn/
我真的很喜欢rsp的回答。特别是“没有循环”部分。尽管如此,我发现代码并不那么直观。我知道这个问题来自两个数组场景,并且已经有 7 年多了,但是由于这个问题在搜索用大括号替换字符串时在 google 上显示为 #1,并且作者要求类似的设置 我很想提供另一种解决方案。
话虽如此,复制粘贴解决方案可以使用:
这个 资源 确实帮助我构建并理解上面的代码,并了解有关 JavaScript 正则表达式的更多信息。
I really like rsp's answer. Especially the 'Without a loop' section. Nonetheless, I find the code not that intuitive. I understand that this question comes from the two arrays scenario and that is more than 7 years old, but since this question appears as #1 on google when searching to replace a string with curly braces and the author asked for a similar setup I am tempted to provide another solution.
That being said, a copy and paste solution to play around with:
This resource really helped me to build and understand the code above and to learn more about regex with JavaScript in general.