简体   繁体   中英

How to search for a string with regex and change only part of it?

How do you match using /[az].\\s[az]/g but only want to change the period to a comma?

For example:

"asdf. Aasdfcs. adGDS$gGB. Basdf".replace(/[a-z]\.\s[a-z]/g, ", ")

This will match "s. a", but I want the result to be "asdf. Aasdfcs, adGDS$gGB. BasdfB" without altering the letters, just the period to a comma. Anything could come before or after this string.

By using capture groups, of course! Use parenthesis to form a group and $n to access the group:

"asdfcs. adGDS$gGB".replace(/([a-z])\.\s([a-z])/g, "$1, $2");

For your convenience, see the result with this snippet:

 alert("asdfcs. adGDS$gGB".replace(/([az])\\.\\s([az])/g, "$1, $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