简体   繁体   English

如何使用正则表达式匹配对象键并替换为其值?

[英]How to use regex to match object key and replace with its value?

I'm still new with Javascript and I'm not entirely sure how to go about this. 我对Javascript还是很陌生,我也不完全确定该怎么做。

I want it to match the key field and replace it with its value. 我希望它与键字段匹配并用其值替换它。

const state = {
"NY": "New York"
}

You live in NY to You live in New York 你住在纽约,住在纽约

The list is going to be quite long with all the states so I think I'll have to use objects. 所有状态的清单将很长,因此我认为我必须使用对象。 Any help would be appreciated! 任何帮助,将不胜感激! Thank you in advance! 先感谢您!

EDIT>>> 编辑>>>

Thank you so much to those that replied! 非常感谢那些回答! I made a list of all the states for USA, Canada, and Mexico to their full name here: https://gist.github.com/PepperAddict/b8c6c80af4a17908fd98378b4375047e 我在此处列出了美国,加拿大和墨西哥的所有州的全名: https : //gist.github.com/PepperAddict/b8c6c80af4a17908fd98378b4375047e

using the code that was provided, I was able to change them all to their full name. 使用提供的代码,我可以将它们全部更改为全名。

Thank you thank you thank you! 谢谢你,谢谢你,谢谢你!

You don't need regex, use the keys from the object state 您不需要正则表达式,使用对象state的键

Object.keys(state).forEach(k => str = str.replace(k, state[k]));

 const state = { "NY": "New York" }; var str = "You live in NY"; Object.keys(state).forEach(k => str = str.replace(k, state[k])); console.log(str); 

Using regex to replace the whole set of matches: 使用正则表达式替换整个匹配项:

 const state = { "NY": "New York" }; var str = "You live in NY and again in NY"; Object.keys(state).forEach(k => str = str.replace(new RegExp(`\\\\b${k}\\\\b`, 'g'), state[k])); console.log(str); 

We can make use of template literals and map it will return an array which you can then do what you want with. 我们可以利用模板文字并映射它会返回一个数组,然后您可以使用它进行操作。

 const state = { "NY": "New York" } console.log(Object.keys(state).map(s => `You live in ${state[s]}`)) 

If you're planning to do this with a user for example 例如,如果您打算与用户一起这样做


 const state = { "NY": "New York" } const user = { name: "joe", state: "NY", liveIn: () => `You live in ${state[user.state]}` } console.log(user.liveIn()) 

if you are sure the last word is key . 如果您确定最后一个字是key Then you can skip foreach by following. 然后,您可以按照以下步骤跳过foreach

const state = {
"NY": "New York"
}

var a = "You live in NY";

b = a.split(" ");

b = b[b.length - 1];


a.replace(b, state[b]);

Console.log(a); 

Output 产量

"You live in New York"

 const states = { "CA": "California", "NY": "New York" } var input = "I'm from CA, thinking of moving to NY but not sure, I still really like CA." var regexStr = Object.keys(states).join("|") var statesRgx = new RegExp(`\\\\b(${regexStr})\\\\b`, 'g') console.log(statesRgx) function stateReplace(str){ return str.replace(statesRgx, val => states[val]) } console.log(stateReplace(input)) 

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

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