khernik
khernik

Reputation: 2091

Replace occurance in a string with the result

I have the following string:

{"key1":"value1","key2":"value2","key3":"value3"}

I want to convert it into this:

{key1:"value1",key2:"value2",key3:"value3"}

So I did something like this:

var output = str.replace(/"(.*?)":/, "$1:");

This way I get:

{key1:"value1","key2":"value2","key3":"value3"}

So it works for the first key, but not for the rest. How can I use the replace method to replace all occurrences like I showed here?

Upvotes: 0

Views: 68

Answers (2)

elad.chen
elad.chen

Reputation: 2425

Use a global flag with your regex

str.replace(/"(.*?)":/g, "$1:");

Upvotes: 6

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167192

You need to change the regex:

var output = str.replace(/"(.*?)":/g, "$1:");

Upvotes: 2

Related Questions