gpt4 book ai didi

Javascript - 替换特殊字符中的字符串的一部分

转载 作者:行者123 更新时间:2023-11-30 07:21:26 24 4
gpt4 key购买 nike

我有 2 个具有值的 javascript 变量:

var Name = 'John';
var Age = '14';

和另一个看起来像这样的字符串变量:

var message = 'I am **Name** and my age is **Age**';

如何将 NameAge 变量的值注入(inject)到 message 字符串中以替换 **Name** **Age** 的值为“John”和“14”?

var newmessage = 'I am John and my age is 14';

是否有我可以用来执行此操作的 javascript 函数?

最佳答案

使用String#replace方法并从 window 对象获取变量(仅当变量在全局上下文中定义时才有效,其他方式你需要使用 eval() 方法,我不喜欢使用。)。

var Name = 'John';
var Age = '14';
var message = 'I am **Name** and my age is **Age**';
var newmessage = message.replace(/\*\*([\w\d]+)\*\*/g, function(m, m1) {
return window[m1];
});

console.log(newmessage)


或者使用对象而不是变量来存储值,这样即使它没有在全局上下文中定义,您也可以轻松获取值。

var obj = {
Name: 'John',
Age: '14'
};
var message = 'I am **Name** and my age is **Age**';
var newmessage = message.replace(/\*\*([\w\d]+)\*\*/g, function(m, m1) {
return obj[m1];
});

console.log(newmessage)

关于Javascript - 替换特殊字符中的字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40713486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com