Skip to content
Advertisement

Regex to select words with spaces for subsititution

I have string in JS which where I need to add ' to the values. Example: task: task one, client: Mr jhon will be converted to task:'task one', client: 'Mr Jhon'

Think of these string as user entered search query. This is then sent to the backed for the searching. The values need to be enclosed in '

Complexities

  • taskname: one two three, client: Mr Jhon there can be more than 2 words
  • taskname: one two, client: Mr Jhon more than 1 space
  • taskname:one,client: Mr Jhon can be singe word without space
  • priority:1,groupname: Mr Singh the name of can be anything
  • priority:1,task: Mr Singh,planet:pluto,done:Yes There can be more than 2 data points

I am using below code to convert in the string in Javascript.

let myStr = `taskname: task one`
myStr = `${myStr},`
const finalStr = myStr.replace(/:((?:w*s*)+),/g, `:'$1',`)
console.log(finalStr)

Question 1: Is the regex performant?

PS: I will be using this in Node JS server.

Advertisement

Answer

Maybe something like this would work for you

let myStr = `taskname: task  one, client: Mr jhon
taskname: one two three, client: Mr Jhon there can be more than 2 words
taskname: one     two, client: Mr Jhon more than 1 space
taskname:one,client: Mr Jhon can be singe word without space
priority:1,groupname: Mr Singh the name of can be anything
priority:1,task: Mr Singh,planet:pluto,done:Yes There can be more than 2 data points`;

const finalStr = myStr.replace(
  /((?<=^w+:)(.*?)(?=,)|(?<=w+:)(.*?)(?=,)|(?<=w+:)(.*?)$)/gim,
  (match) => `'${match.trim()}'`
);

console.log(finalStr);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement