javascriptreactjsregex

Extract user data using regex from react mention


Hi please help me to extract to get Name and username from this content below:

Hello @[Walter White](walter) with @[中本聪](satoshi1) are you @[Gustavo "Gus" Fring](gus) ok?

I don't really understand how regex works, so i try this formula:

@[[A-Za-z0-9 ]+]

only show @[name], i want to make the mention change to Link.

I'm using React JS, thank you


Solution

  • You can try the regex I made with the desired outcome.

    const text = "Hello @[Walter White](walter) with @[中本聪](satoshi1) are you @[Gustavo \"Gus\" Fring](gus) ok?";
    
    const regex = /@\[(.*?)\]\((.*?)\)/g;
    let matches;
    const result = [];
    
    while ((matches = regex.exec(text)) !== null) {
      result.push({ name: matches[1], username: matches[2] });
    }
    
    console.log(result);