2

I would like to replace many terms using regexp with a single call, is it possible? In the example below I want to replace all spaces and ö chars to _ and - respectively.

Pattern: ( +)|(ö+)

Source string: Abc dfö/ab.ai dois ö

Replace pattern: $1_$2-

Current result: Abc _-df_ö-/ab.ai _-dois _-_ö-

Expected result: Abc_df-/ab.ai_dois_-

Thanks.

1 Answer 1

2

Use a callback function to check which group "worked" and replace accordingly:

var re = /( +)|(ö+)/g; 
var str = 'Abc dfö/ab.ai dois ö';
var result = str.replace(re, function (m, g1, g2) {
    return g1 ? "_" : "-";
});
document.getElementById("r").innerHTML = result;
<div id="r"/>

The second argument in .replace() accepts a function.

A function to be invoked to create the new substring (to put in place of the substring received from parameter #1).

See more details on the callback function parameters in the Specifying a function as a parameter section.

UPDATE

You may map the symbols (since you are searching for single symbols) to the replacement symbols, and specify them all in 1 regex. Then, in the callback function, you can get the necessary value using the first character from the matched text.

var rx = / +|ö+|ë+|ü+/g;
str = "Abc dfö/ab.ai dois ööö üüü";
console.log(str);
map = { 
    " ": "_", 
    "ö": "-", 
    "ü": "+", 
    "ë": "^"
};
result = str.replace(rx, function (match) {
    return map[match[0]]; }
);
console.log(result);
// Abc dfö/ab.ai dois ööö üüü => Abc_df-/ab.ai_dois_-_+

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

4 Comments

Thanks @stribizhev but I need a solution more generic in case of I have for example /( +)|(ö+)|(ä+)|(ë+)|(ü+)|(etc...+)/g
XY problem? That is not good. Anyway, you will have 2 choices: either use the callback specifying the necessary amount of capturing groups, or use chained replace() methods. You cannot specify multiple literal replacements in the replacement pattern.
yes @stribizhev... I was trying to avoid that approach so looks like that will be the way. thanks and upped :)
one could change the OR connected pattern in a way that its remaining capturing group can be used as key of a map of surrogate/replacement characters. ``` var regX = /( |ö)+/g, str = "Abc dfö/ab.ai dois ö", map = { " ": "_", "ö": "-", }, result = str.replace(regX, function (match, $1) { return map[$1]; }) ; console.log("str, result : ", str, result);```

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.