替换大括号内的文本 JavaScript

发布于 2024-10-24 07:20:37 字数 713 浏览 13 评论 0 原文

我正在尝试使用 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 中的简单字符串!是的,一个字符串!”。

发生的情况如下:

  1. 我们得到一个字符串,其中大括号中的值需要替换,
  2. 循环使用“replaceArray”来查找大括号中需要替换的所有值
  3. ,这些值以及大括号将被替换为“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:

  1. we are given a string with values in braces that need replaced
  2. a loop uses "replaceArray" to find all of the values in curly braces that will need replaced
  3. 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

分分钟 2024-10-31 07:20:37

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

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

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]);
}
逆夏时光 2024-10-31 07:20:37

我发现做到这一点的最好方法是使用内联替换函数,就像其他人提到的那样,以及我从谁那里借来的。特别感谢 @yannic-hamann 的正则表达式和清晰的示例。我并不担心性能,因为我这样做只是为了构建路径。

我在 MDN 文档 中找到了解决方案。

const interpolateUrl = (string, values) => string.replace(/{(.*?)}/g, (match, offset) => values[offset]);

const path = 'theresalways/{what}/inthe/{fruit}-stand/{who}';
const paths = {
  what: 'money',
  fruit: 'banana',
  who: 'michael',
};

const expected = 'theresalways/money/inthe/banana-stand/michael';

const url = interpolateUrl(path, paths);

console.log(`Is Equal: ${expected === url}`);
console.log(`URL: ${url}`)

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.

const interpolateUrl = (string, values) => string.replace(/{(.*?)}/g, (match, offset) => values[offset]);

const path = 'theresalways/{what}/inthe/{fruit}-stand/{who}';
const paths = {
  what: 'money',
  fruit: 'banana',
  who: 'michael',
};

const expected = 'theresalways/money/inthe/banana-stand/michael';

const url = interpolateUrl(path, paths);

console.log(`Is Equal: ${expected === url}`);
console.log(`URL: ${url}`)

思念绕指尖 2024-10-31 07:20:37

字符串是不可变的

JavaScript 中的字符串是不可变的。这意味着这永远不会像您期望的那样工作:

myString.replace(x, y);
alert(myString);

这不仅仅是 .replace() 的问题 - 没有任何东西可以改变 JavaScript 中的字符串。你可以做的是:

myString = myString.replace(x, y);
alert(myString);

正则表达式文字不插入值

JavaScript 中的正则表达式文字不插入值,所以这仍然不起作用:

myString = myString.replace(/\{replaceArray[i]\}/gi, replaceWith[i]);

你必须做这样的事情:

myString = myString.replace(new RegExp('\{'+replaceArray[i]+'\}', 'gi'), replaceWith[i]);

但这有点混乱,所以你可以先创建一个正则表达式列表:

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

如您所见,您还可以使用 i i i i i i i i i i i ReplaceArray.length 而不是 i <= ReplaceArray.length - 1 来简化循环条件。

更新 2017

现在您可以使其变得更加简单:

var regexes = replaceArray.map(string => new RegExp(`\{${string}\}`, 'gi'));
for(var i = 0; i < replaceArray.length; i ++) {
  myString = myString.replace(regexes[i], replaceWith[i]);
}

无需循环

您只需执行一次即可,而不是一遍又一遍地循环和应用 .replace() 函数:

var mapping = {};
replaceArray.forEach((e,i) => mapping[`{${e}}`] = replaceWith[i]);
myString = myString.replace(/\{\w+\}/ig, n => mapping[n]);

请参阅 演示

模板引擎

您基本上是在创建自己的模板引擎。如果您想使用现成的解决方案,请考虑使用:

或类似的东西。

您尝试使用 Mustache 执行的操作示例如下:

var myString = "This is {{name}}'s {{adjective}} {{type}} in JavaScript! Yes, a {{type}}!";

var myData = {name: 'John', adjective: 'simple', type: 'string'};

myString = Mustache.to_html(myString, myData);

alert(myString);

请参阅 DEMO

Strings are immutable

Strings in JavaScript are immutable. It means that this will never work as you expect:

myString.replace(x, y);
alert(myString);

This is not just a problem with .replace() - nothing can mutate a string in JavaScript. What you can do instead is:

myString = myString.replace(x, y);
alert(myString);

Regex literals don't interpolate values

Regular expression literals in JavaScript don't interpolate values so this will still not work:

myString = myString.replace(/\{replaceArray[i]\}/gi, replaceWith[i]);

You have to do something like this instead:

myString = myString.replace(new RegExp('\{'+replaceArray[i]+'\}', 'gi'), replaceWith[i]);

But this is a little bit messy, so you may create a list of regexes first:

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

As you can see, you can also use i < replaceArray.length instead of i <= replaceArray.length - 1 to simplify your loop condition.

Update 2017

Now you can make it even simpler:

var regexes = replaceArray.map(string => new RegExp(`\{${string}\}`, 'gi'));
for(var i = 0; i < replaceArray.length; i ++) {
  myString = myString.replace(regexes[i], replaceWith[i]);
}

Without a loop

Instead of looping and applying .replace() function over and over again, you can do it only once like this:

var mapping = {};
replaceArray.forEach((e,i) => mapping[`{${e}}`] = replaceWith[i]);
myString = myString.replace(/\{\w+\}/ig, n => mapping[n]);

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:

var myString = "This is {{name}}'s {{adjective}} {{type}} in JavaScript! Yes, a {{type}}!";

var myData = {name: 'John', adjective: 'simple', type: 'string'};

myString = Mustache.to_html(myString, myData);

alert(myString);

See DEMO.

枯寂 2024-10-31 07:20:37

这是一个接受字符串和替换数组的函数。它足够灵活,可以重复使用。唯一的问题是,您需要在字符串中使用数字而不是字符串。例如,

var str = "{0} membership will start on {1} and expire on {2}.";

var arr = ["Jamie's", '11/27/14', '11/27/15'];

function personalizeString(string, replacementArray) {
  return string.replace(/{(\d+)}/g, function(match, g1) {
    return replacementArray[g1];
  });
}

console.log(
  personalizeString(str, arr)
)

演示: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.,

var str = "{0} membership will start on {1} and expire on {2}.";

var arr = ["Jamie's", '11/27/14', '11/27/15'];

function personalizeString(string, replacementArray) {
  return string.replace(/{(\d+)}/g, function(match, g1) {
    return replacementArray[g1];
  });
}

console.log(
  personalizeString(str, arr)
)

Demo: https://jsfiddle.net/4cfy7qvn/

装纯掩盖桑 2024-10-31 07:20:37

我真的很喜欢rsp的回答。特别是“没有循环”部分。尽管如此,我发现代码并不那么直观。我知道这个问题来自两个数组场景,并且已经有 7 年多了,但是由于这个问题在搜索用大括号替换字符串时在 google 上显示为 #1,并且作者要求类似的设置 我很想提供另一种解决方案。

话虽如此,复制粘贴解决方案可以使用:

var myString = "This is {name}'s {adjective} {TYPE} in JavaScript! Yes, a { type }!";

var regex = /{(.*?)}/g;
myString.replace(regex, (m, c) => ({
    "name": "John",
    "adjective": "simple",
    "type": "string"
})[c.trim().toLowerCase()]);

这个 资源 确实帮助我构建并理解上面的代码,并了解有关 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:

var myString = "This is {name}'s {adjective} {TYPE} in JavaScript! Yes, a { type }!";

var regex = /{(.*?)}/g;
myString.replace(regex, (m, c) => ({
    "name": "John",
    "adjective": "simple",
    "type": "string"
})[c.trim().toLowerCase()]);

This resource really helped me to build and understand the code above and to learn more about regex with JavaScript in general.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文