简体   繁体   中英

regex match replace multiple times (javascript)

I have to normalize a file removing part of the text. An sample string extracted from the file is the following:

"a":{"$":"word"}, "b":{"$":"100"}, "c": {"$":"2017-02-08T16:20:36+13:00"}

The target should be:

"a":"word","b":"100","c":"2017-02-08T16:20:36+13:00"

I identified a regular expression that matches my requirement:

var regex = /{"\$":(.*)"}/g;

But when I do the replacement (found similar code in stackoverflow):

let targetString = sourceString.replace(regex, "$1");

I have to problems, only the first match is replaced and a "}" is not handled properly.

"a":"word"},"b":{"$":"100"},"c":{"$":"2017-02-08T16:20:36+13:00

Below the full code and the console log:

let jsonC1 = `"a":{"$":"word"}, "b":{"$":"100"}, "c":{"$":"2017-02-08T16:20:36+13:00"}`;
//matches (regex) all white spaces and replace them with no space
let jsonN = jsonC1.replace(/\s/g,'');
console.log(`jsonN: ${jsonN}`);
var regex = /{"\$":(.*)"}/g;
let jsonS = jsonN.replace(regex, "$1");
console.log(`jsonS: ${jsonS}`);

jsonN: "a":{"$":"word"},"b":{"$":"100"},"c":{"$":"2017-02-08T16:20:36+13:00"}

jsonS: "a":"word" } ,"b": {"$":"100"} ,"c": {"$":"2017-02-08T16:20:36+13:00

Cheers, Giovanni

Try using this:

const targetString = data.replace(/\s*{".*?"\s*:\s*"(.*?)"}\s*/g, `"$1"`)

\\s* is used to remove all extra spacing.

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