简体   繁体   中英

Javascript - Use regex to find multiple occurrences of a pattern in a string

I have a string in this format

"{{abc}}, {{def}}, some text {{ghi}}, some other text {{jkl}}"

And I would like to replace each of {{...}} with some string based on what is ... (that comes out of json and not an issue) and stuck with what regex pattern to use. Closest I could come was to /{{(.*)}}/gi , but that returns the whole string as the same has {{ and }} at ends. Here's the code I have tried

let str = "{{abc}}, {{def}}, some text {{ghi}}, some other text {{jkl}}";
let regex = /{{(.*)}}/gi;
let result;
let indices = [];
let results = [];
while ((result = regex.exec(str))) {
    indices.push(result.index);
    results.push(result[0]);
}

Any help will be highly appreciated

This will do it: \\{\\{(.*?)\\}\\}

You need to escape the } via \\ , also set the non greedy operator ?

See: https://regex101.com/r/F9xdgx/2

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