0

I have a function:

function process(str) {
    if (str == "Mary") {
        return "Sally";
    } else {
        return str;
    }
}

And I have some text:

John Smith
Mary Smith
Peter Smith
Mary Davis

I want it become:

John Smith
Sally Smith
Peter Smith
Sally Davis

But none of this work:

text = text.replace(/([a-zA-Z]+)\s([a-zA-Z]+)([\n]{0,1})/g,process(RegExp.$1) + " " + process(RegExp.$2)+"\$3");
//RegExp.$n is undefined

or

text = text.replace(/([a-zA-Z]+)\s([a-zA-Z]+)([\n]{0,1})/g,process('\$1') + " " + process('\$2')+"\$3");
//I got this exact string '$1' in process()

So how can I reuse the matches value and pass it into another function?

1

1 Answer 1

1

String.prototype.replace can take a function as a second parameter. This function will have the match of the regex as the first parameter. So you only have to call replace like this:

var result = str.replace(/([a-zA-Z]+)/g, process);

Example: https://jsfiddle.net/71k6x3gd/

I also changed the regex to match all words, since surnames are never "Mary", it still works as expected. If you want to keep your regex, you would need to change the function to work with the parenthesized submatches. In the replacement function, these are the arguments following the match. Something like this:

function process(matchedString, firstName, secondName, optionalReturn) {
    if (firstName == "Mary") {
        firstName = "Sally";
    }
    return firstName + " " + secondName + optionalReturn;
};

Example: https://jsfiddle.net/71k6x3gd/1/

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.