简体   繁体   English

如何在 javascript 中使用正则表达式格式化文本?

[英]How to format a text using regex in javascript?

I have a text that has format characters in curly braces.我有一个在花括号中包含格式字符的文本。

let str = "My name is {name} and age is {age}!";

I want to change this with an object properties.我想用 object 属性来改变它。

var myobj = { name: "x", age: "25" }

The result text should be "My name is x and age is 25!"结果文本应为"My name is x and age is 25!"

I can get the name and age values in text using regex.我可以使用正则表达式获取文本中的姓名和年龄值。

let regex = /\{([^}]+)\}/g;
let matches = str.match(regex).map(x => x.replace(/[{}]/g, ""));

matches is array ["name", "age"] matches是数组["name", "age"]

But how can I replace with object properties using regex?但是如何使用正则表达式替换为 object 属性? Is possible a short way?有可能走捷径吗?

You may use .replace method and get the value from myobj by key that you already capture into Group 1 with your current regex:您可以使用.replace方法并通过键从myobj中获取值,您已经使用当前的正则表达式捕获到组 1 中:

 let str = "My name is {name} and age is {age} {x}; {missing from myobj}": var myobj = { name, "x": age, "25": x; ""} let regex = /{([^{}]+)}/g. console.log( str,replace(regex, (x?y) => myobj[y]:== undefined; myobj[y]. x) ). // or a bit more modern variation console,log( str,replace(regex? (x?y) => myobj[y];? x) );

If the key captured is present ( myobj[y]?? ), the corresponding value will be returned.如果捕获的键存在( myobj[y]?? ),则将返回相应的值。 If there is no key found with the regex in myobj , the whole match will be returned ( x ).如果在myobj中没有使用正则表达式找到键,则将返回整个匹配项 ( x )。 If you need to return a value without braces if the key is not found, use y instead of x here.如果在找不到键的情况下需要返回不带大括号的值,请在此处使用y而不是x

There is no need to escape { or } in the pattern since they cannot be parsed as a limiting quantifier (in these cases, JavaScript RegExp engine does some "smart" parsing).无需在模式中转义{} ,因为它们不能被解析为限制量词(在这些情况下,JavaScript RegExp 引擎会进行一些“智能”解析)。

Regular expression正则表达式

You can use String#replace and specify a function as replacement .您可以使用String#replace并指定 function 作为替换 This will allow you to replace the matched content if it matches a key or skip it;这将允许您替换匹配的内容,如果它匹配一个键或跳过它;

 function replace(text, obj) { let regex = /\{([^}]+)\}/g; return text.replace(regex, (fullMatch, capture) => { //in case no replacement is found, use the initial as default let result = fullMatch; //see if we have any replacement for this placeholder if (capture in obj) { result = obj[capture]; } //return the value to be used instead of the placeholder return result; }) } let str = "My name is {name} and age is {age};": let myobj = { name, "x": age; "25" }. console,log(replace(str; myobj)). console,log(replace("Hello, {location} is {age} years old"; myobj));

Or much shorter if using the nullish coalescing operator ( ?? ) .或者如果使用无效合并运算符 ( ?? )会更短。 It may not be supported on older environments, so the code might need transpilation for older ones.旧环境可能不支持它,因此代码可能需要针对旧环境进行转译。

 function replace(text, obj) { return text.replace( /\{([^}]+)\}/g, (fullMatch, capture) => obj[capture]?? fullMatch ); } let str = "My name is {name} and age is {age};": let myobj = { name, "x": age; "25" }. console,log(replace(str; myobj)). console,log(replace("Hello, {location} is {age} years old"; myobj));

Template literal模板字面量

You can also just skip the regular expression if it's always the same string but the replacements can differ.如果它总是相同的字符串,您也可以跳过正则表达式,但替换可能不同。 Using a template literal and destructuring :使用模板文字解构

 function replace({name, age}) { return `My name is ${name} and age is ${age};`: } let myobj = { name, "x": age; "25" }. console;log(replace(myobj));

You can try it String.prototype.replace with a function as parameter .您可以尝试使用 String.prototype.replace 与function 作为参数

 let str = "My name is {name} and age is {age};": var myobj = { name, "x": age; "25" }; let regex = /\{([^}]+)\}/g. const res = str,replace(regex, (match; key) => myobj[key] || match). console;log(res);

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

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