Home > Back-end >  Regexp replace any single word
Regexp replace any single word

Time:12-13

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 ?

CodePudding user response:

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

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

and replace the matching character with:

node.$1

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

CodePudding user response:

You can try this approach:

Logic:

  • Split string using equals to(=) to get LHS and RHS as this operation only needs to be done on RHS.
  • Create a regex to match any word period combination. You can also use non-space characters(/[\s] /) as this will cover bracket notations and underscore as well
  • For each match, check if they do not have period(.) in it. If not, you can append prefix and return it.
  • Join both halves and return the string

let origin = 'page.a = b'
let o1 = 'page.a = b && page.a < c'

function transformStr(str, prefix) {
  const regex = /([\w.] )/g;
  const [lhs, rhs] = str.split('=')
  const newRhs = rhs.replace(regex, (part) => {
    return /^\w $/.test(part) ? `${prefix}.${part}` : part
  })
  return `${lhs}=${newRhs}`
}

console.log(transformStr(origin, 'node'))
console.log(transformStr(o1, 'node'))

As an extension, you can add support for special characters that can exists in a variable. This approach matches non-spaced character groups and processes only the ones that has only word characters or underscore or dollar

function transformStr(str, prefix) {
  const regex = /([^\s] )/g;
  const [lhs, rhs] = str.split('=')
  const newRhs = rhs.replace(regex, (part) => {
    return /^[\w\$] $/.test(part) ? `${prefix}.${part}` : part
  })
  return `${lhs}=${newRhs}`
}

console.log(transformStr('page.a = b', 'node'))
console.log(transformStr('page.a = b && page.a < c', 'node'))
console.log(transformStr('page._a = _b && page.a < $c', 'node'))

  • Related