Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript: Replace values in a string based on an array, efficient solution

I have a sample code but I am looking for the most efficient solution. Sure I can loop twice through the array and string but I was wondering if I could just do a prefix search character per character and identify elements to be replaced. My code does not really do any of that since my regex is broken.

const dict = {
    '\iota': 'ι',
    '\nu': 'ν',
    '\omega': 'ω',
    '\'e': 'é',
    '^e': '?'
}
const value = 'Ko\iota\nu\omega L'\'ecole'

const replaced = value.replace(/w+/g, ($m) => {
  console.log($m)
  const key = dict[$m]
  console.log(key)
  return (typeof key !== 'undefined') ? key : $m
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your keys are not fully word characters, so w+ will not match them. Construct the regex from the keys instead:

// https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
const escapeRegExp = string => string.replace(/[.*+?^${}()|[]\]/g, '\$&');

const dict = {
    '\iota': 'ι',
    '\nu': 'ν',
    '\omega': 'ω',
    '\'e': 'é',
    '^e': '?'
}
const value = 'Ko\iota\nu\omega L'\'ecole'

const pattern = new RegExp(Object.keys(dict).map(escapeRegExp).join('|'), 'g');
const replaced = value.replace(pattern, match => dict[match]);
console.log(replaced);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...