Search code examples
javascriptregexregexp-replace

Regexp replace any single word


I need to replace 'page.a = b' with 'page.a = node.b'. In a word, i need to turn single word 'b' into 'node.b'; In other word, the string 'page.a = b && page.a < c' shold be transformed into 'page.a = node.b && page.a < node.c', just add 'node.' as the prefix to the single words. Can anyone help me with this? I think the js regexp can work but just cannot find the way with it.

let origin = 'page.a = b'
let expected = 'page.a = node.b';

How do i get the expected string from the origin ?


Solution

  • You can use negative lookarounds to look for words that aren't preceded by or followed by a dot or a word character:

    (?<![.\w])(\w+)(?![.\w])
    

    and replace the matching words with:

    node.$1
    

    https://regex101.com/r/GD2N9g/5