stackoverflow_user
stackoverflow_user

Reputation: 301

How to replace a multiple patterns in the same string using regex and javascript?

i want to replace multiple patterns in the same string using regex and javascript.

What i am trying to do? i have a string for example

string = "hello i am [12@fname lname] and i am referring this user [23@fname1 lname1]"

now i get all the strings with [] using regex

const get_strings_in_brackets = string.match(/\[(\d+@[\w\s]+)]/g); 

so get_strings_in_brackets will have ["[12@fname lname]", "[23@fname1 lname1]"]

now i want these to be replaced with string "<some-tag id="12"/> "<some-tag id="23"/> in the string "hello i am [12@fname lname] and i am referring this user [23@fname1 lname1]"

also this number 12 in this string "<some-tag id="12"/> is got from the string ["[12@fname lname]" before @ character.

What i have tried to do?

i have tried to replace for only one string withing brackets meaning for the example below string ="hello i am [12@fname lname1]"

const extracted_string_in_brackets = string.match(/\[(\d+@[\w\s]+)]/g);
const get_number_before_at_char = 
    extracted_string_in_brackets[0].substring(1, 
    extracted_string_in_brackets[0].indexOf('@'));
const string_to_add_in_tag = `<some-tag 
    id="${get_number_before_at_char}"/>`;
const final_string = string.replace(extracted_string_in_brackets, 
    string_to_add_in_tag);

The above code works if i have only one string within square brackets. But how do i do it with multiple strings in brackets and replacing that with tag string that is for example .

Could someone help me solve this. thanks.

Upvotes: 0

Views: 1356

Answers (1)

georg
georg

Reputation: 214949

Just use a group reference in your replacement:

string = "hello i am [12@fname lname] and i am referring this user [23@fname1 lname1]"

newstr = string.replace(/\[(.+?)@(.+?)\]/g, '<some-tag id="$1"/>')

console.log(newstr)

Upvotes: 2

Related Questions