I'm looking to replace a word that's not in quotes, whether single or double, accounting for escapes as well.
My test case:
Trying to replace
`obj1 = {
name: person,
favoriteQuote: "I am my own person.",
}`
person
with "Joe"
.
Expected result:
`obj1 = {
name: "Joe",
favoriteQuote: "I am my own person.",
}`
I saw this question: Match and replace a word not in quotes (string contains escaped quotes) which I thought was similar and could be a good starting point the accepted answer does not work at all:
https://regex101.com/r/Lfan64/3
What's a regex that could do this? Thanks.
Broader context since the question was confusing:
It looks like this:
people = ["Joe", "Bob", "Sally"]
people.forEach(function (person) {
saveEval(template.replace(regex, person))
});
If I understand your question correctly, you have a string and want to replace person
with "Joe"
. If so, the following regex may help:
const str = `obj1 = { name: person, favoriteQuote: "I am my own person.", }`; console.log( str.replace(/(?<=name:\s?)[^,|\n]+/gm, ' "Joe"') );
And this is how you could loop through an array:
const str = `obj1 = { name: person, favoriteQuote: "I am my own person.", }`; const people = ["Joe", "Bob", "Sally"]; people.map((v) => console.log(str.replace(/(?<=name:\s?)[^,|\n]+/gm, ` "${v}"`)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.