Marcelo Idemax
Marcelo Idemax

Reputation: 2810

Replace strings via regexp by groups in Javascript

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.

Upvotes: 2

Views: 324

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626816

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_-_+

Upvotes: 2

Related Questions