1

I am getting a sometimes random string that will always contain [] with special string inside of it. I would like to use the text inside each bracket and use it in a function to replace the text inside each bracket. Here is an example: So far I have

let string = 'test [a] test2 [b]'
let test = string.replace(/\[(.+?)\]/g, ""+getValue(text inside bracket replaced here)+"")

function getValue(text) {
    //this function will return a value based on the certain text it receives
}
console.log(test)

'test [replaced text based on a value] test2 [replaced text based on b value]'

Thanks for the help in advance.

0

1 Answer 1

1

The second argument of .replace can be a replacer function, so you can put getValue there. The capture group will be in the second argument, so you'll have to alter getValue's parameter list:

let string = 'test [a] test2 [b]'
let test = string.replace(/\[(.+?)\]/g, getValue);

function getValue(wholeMatch, textInsideBrackets) {
    //this function will return a value based on the certain text it receives
}
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, clear example - nice one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.