Reputation: 1008
I'm still new with Javascript and I'm not entirely sure how to go about this.
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
using the code that was provided, I was able to change them all to their full name.
Thank you thank you thank you!
Upvotes: 1
Views: 4929
Reputation: 353
if you are sure the last word is key
. Then you can skip foreach by following.
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"
Upvotes: 1
Reputation: 33726
You don't need regex, use the keys from the object 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);
Upvotes: 2
Reputation: 3368
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))
Upvotes: 1
Reputation: 3452
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())
Upvotes: 1