简体   繁体   中英

Replace all in JavaScript Regex

i have below string from which I have to extract username and ID.

This is a string which has a @[User Full Name](contact:1)  data inside.

To get username and contact id from above string I am using this regex pattern.

    var re = /\@\[(.*)\]\(contact\:(\d+)\)/;
    text = text.replace(re,"username:$1 with ID: $2");
// result == username: User Full Name with ID: 1

It works perfectly now issue is I have multiple usernames in string, I tried using /g (global) but its not replacing properly: Example string:

This is a string which has a @[User Full Name](contact:1)  data inside. and it can also contain many other users data like  @[Second Username](contact:2) and  @[Third username](contact:3) and so many others....

when used global I get this result:

var re = /\@\[(.*)\]\(contact\:(\d+)\)/g;
text = text.replace(re,"username:$1 with ID: $2");
//RESULT from above     
This is a string which has a user username; User Full Name](contact:1) data inside. and it can also contain many other users data like @[[Second Username](contact:2) and @[Third username and ID: 52 and so many others....

You just need a non greedy ? match in your first capture group. By having .* you are matching the most amount possible while if you use .*? , it matches the least amount possible.

/@\[(.*?)\]\(contact:(\d+)\)/

And if the word contact is not always there, you could do..

/@\[(.*?)\]\([^:]+:(\d+)\)/

See working demo

Can't say I can see how your resulting string is going to be usable. How about something like this...

var re = /@\[(.*?)\]\(contact:(\d+)\)/g;
var users = [];
var match = re.exec(text);
while (match !== null) {
    users.push({
        username: match[1],
        id: match[2]
    });
    match = re.exec(text);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM