Maramal
Maramal

Reputation: 3466

Replace a string using regular expression having two variables

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?

Upvotes: 2

Views: 59

Answers (2)

Jared Smith
Jared Smith

Reputation: 21926

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((params, [key], index) => {
  params.append(key, matches[index]);
  return params;
}, new URLSearchParams());

You can call toString() on it to get the modified query string. Generally speaking you want to avoid doing string processing any time there's a readily available richer data type.

Upvotes: 3

Andrew Parks
Andrew Parks

Reputation: 8087

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(''))

Upvotes: 2

Related Questions