简体   繁体   English

Javascript用正则表达式替换为字符串中的变量

[英]Javascript Replace with variable in string with Regular Expression

I want to replace a lot of keywords in string with pre-defined variables, samples as below, but now $1 only shows variable name, not variable content, any one can help me, please!!! 我想用预定义的变量替换字符串中的很多关键字,样本如下,但现在$ 1只显示变量名,而不是变量内容,任何人都可以帮助我,请!!!

Correct: 正确:

1111{t:aa} 1111 {T:AA}
2222{t:bb} 2222 {T:BB}
3333{t:cc} 3333 {T:CC}

To: 至:

1111Test1 1111Test1
2222Test2 2222Test2
3333Test3 3333Test3

Not: 不:

1111aa 1111aa
2222bb 2222bb
3333cc 3333CC

Code: 码:

var aa = "Test1";
var bb = "Test2";
var cc = "Test3";
var str_before = "1111{t:aa}\n2222{t:bb}\n3333{t:cc}";
var str_after = str_before.replace(/\{t:\s*(\w+)\}/g, "$1");
alert(str_before+"\n\n"+str_after);

A regexp constant (ie /.../ syntax) cannot directly refer to a variable. 正则表达式常量(即/.../语法)不能直接引用变量。

An alternate solution would be to use the .replace function's callback parameter: 另一种解决方案是使用.replace函数的回调参数:

var map = {
    aa: 'Test1',
    bb: 'Test2',
    cc: 'Test3'
};

var str_before = "1111{t:aa}\n2222{t:bb}\n3333{t:cc}";
var str_after = str_before.replace(/{t:(\w+)}/g, function(match, p1) {
    return map.hasOwnProperty(p1) ? map[p1] : '';
});

This further has the advantage that your mapping from name to value is now easily configurable , without requiring a separately declared variable for each one. 这进一步的优势在于,您现在可以轻松配置从名称到值的映射,而无需为每个映射单独声明变量。

There is a NPM package out there for this, it allows you to pass in the string, and an array of variables you want to replace them with. 这里有一个NPM包,它允许您传入字符串,以及要替换它们的变量数组。 Find a simple example along with the link to the package below: 找到一个简单的示例以及下面的包的链接:

Example: 例:

var str = "This is a {0} string for {1}"
var newStr = stringInject(str, ["test", "stringInject"]);

// This is a test string for stringInject 

NPM / GitHub links: NPM / GitHub链接:

https://www.npmjs.com/package/stringinject https://www.npmjs.com/package/stringinject

https://github.com/tjcafferkey/stringinject https://github.com/tjcafferkey/stringinject

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM