2

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

well, learned something new today, thank you.
2

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

1 Comment

Thank you, but I rather do the URL approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.