Home > Enterprise >  Replace a string using regular expression having two variables
Replace a string using regular expression having two variables

Time:11-20

I need to replace two strings using regular expression value replacement so the resulting string is $?tlang=es&text=Hello world, so I didn't know to use here String.prototype.replace().

const value = "Hello world"
const queryString = "?tlang=es&text=$1"

In this scenary, value and queryString are hard-coded, but in "real life" it should be the result of a regular expression group capturing like line.match(/msgid \"(.*)\"/) where line is an iterated text line and queryString is what the user submitted.

I thought I just could do this, but maybe it's too much effort where there is a better solution (that I couldn't find):

const line = "Full name: John Doe" // text input
const sourcePattern = /Full name: (.*) (.*)/ // user input
let queryString = 'name=$1&lname=$2' // user input
const matches = line.match(sourcePattern)
matches.splice(0, 1)

for (let i = 0; i < matches.length; i  ) {
    queryString = queryString.replace(`\$${i 1}`, matches[i])
}

Any ideas?

CodePudding user response:

You could compact the code a little as follows:

const line = "Full name: John Doe" // text input
const sourcePattern = /Full name: (.*) (.*)/ // user input
let queryString = 'name=$1&lname=$2' // user input
const [_, ...matches] = line.match(sourcePattern)

console.log(queryString.split(/\$\d /)
  .map((p,i)=>`${p}${matches[i]??''}`).join(''))

CodePudding user response:

Regular expressions are fine to extract the values from the first string. But for working with query strings there's a built in class that helps:

const entries = [...new URLSearchParams(queryString).entries()]

if (matches.length !== entries.length) {
  // handle error
}

const replaced = entries.reduce((str, [key], index) => {
  return `${str}&${key}=${matches[index]}`
}, '');
  • Related