简体   繁体   中英

Replace all occurence regex

I would like to replace all occurent of ", ]" to "]"

I tried:

 const str = 'website , ] asdf asdf , asdf'

 str.replace('/, ]/g',']')

Nothing happens

Regular expression to find all , ] occurences is /, ]/g .

You should also store the new string returned by the replace() method.

 const str = 'website , ] asdf asdf , asdf'; const result = str.replace(/, ]/g, ']'); console.log(result); 

You can use String.replace and supply a regexp with the global flag to replace all of the occurrences.

Use \\s any type of space
Use \\] to match the ]

 const str = "website , ] asdf asdf , asdf"; console.log(str.replace(/,\\s\\]/g, "]")); 

this will work:

str.replace(/, ]/gm,"]");

online regex tester

code generator

str.replace('/, ]/g',']') doesn't change str in-place. You must assign the result to another string variable:

var result = str.replace('/, ]/g',']');
console.log(result)

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