ChrisGciso ChrisGciso - 1 year ago 90
Javascript Question

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

How do you match using /[a-z].\s[a-z]/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.

Answer Source

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(/([a-z])\.\s([a-z])/g, "$1, $2"));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download