RooksStrife
RooksStrife

Reputation: 1747

JS RegEx Find and Replace based on Group

I am trying to search for two characters: 1.', ' and 2. a '('. So if a comma and a space is found replace with just a comma and if the ( is found replace with blank.

Below is what I have and I know I could do two replace, but was looking on combining into one using groups possible... like $1 ='' $2 = ','?

str.replace(/(\()|(,\s)/g, '');

Upvotes: 1

Views: 3925

Answers (4)

FreePhoenix888
FreePhoenix888

Reputation: 6087

The second parameter of the String.prototype.replace can be string or function. Source

Replacement function

If it's a function, it will be invoked for every match and its return value is used as the replacement text.

function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) {
  return replacement;
}

More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_the_replacement

Replacement string

console.log(
  "Your age: 50".replace(/.+?(?<age>\d+)/, "age named capure group: $<age>")
);

More info about what you can use in the replacement string: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_the_replacement

Upvotes: 0

Eduardo Lynch Araya
Eduardo Lynch Araya

Reputation: 824

Two Steps:

Replace ', ' to ','

const regex = /(\,\s)/gm;
const str = `abc, 123( something.`;
const subst = `,`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

Replace ')' to ''

const regex = /(\()/gm;
const str = `abc, 123( something.`;
const subst = ``;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

Mixed Solution:

    regex = /(\,\s)/gm;
    str = `abc, 123( something.`;
    subst = `,`;
    
    // The substituted value will be contained in the result variable
    result = str.replace(regex, subst);
    
    regex = /(\()/gm;
    str = result;
    subst = ``;
    
    // The substituted value will be contained in the result variable
    result = str.replace(regex, subst);
    //
    console.log(result);

If I help you, remember to mark me as the answer to the question

Upvotes: 0

Kraylog
Kraylog

Reputation: 7553

The replace function accepts a function as the second parameter. You can use that to replace any match to whatever you want. The first parameter to the function is the matched string.

See more details here.

Upvotes: 2

anubhava
anubhava

Reputation: 785156

You can use a captured group and back-reference:

str = str.replace(/(,) |\(/g, '$1');

Code Sample:

var str = 'abc, 123( something.'
console.log(str.replace(/(,) |\(/g, '$1'))
//=> "abc,123 something."

RegEx Demo

Upvotes: 0

Related Questions