0

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(/\b\w+\b/g, ($m) => {
  console.log($m)
  const key = dict[$m]
  console.log(key)
  return (typeof key !== 'undefined') ? key : $m
})

1 Answer 1

1

Your keys are not fully word characters, so \b\w+\b 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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.