Regex Match All Single Underscores Surrounded In One Or More Letters Or Numbers

- 1 answer

I'm trying to find all single underscores that are surrounded by one more letters or numbers in a string. E.g:


*Note: the length of the string and number of underscores is unknown. The string may also contain multiple underscores together. *

I'm sure this is easy but I'm not super savvy with regex. This is what I have so far, but it's only matching the first occurrence.


The end goal is to replace the underscores with another character.



Try this regex:


You can use it like this for replacing it with '-'

str.replace(/([a-zA-Z0-9])_([a-zA-Z0-9])/g, "$1-$2")

you can add any other character or string in place of '-'

This regex matches (A-Z or a-z or 0-9), an underscore and (A-Z or a-z or 0-9)


[a-zA-Z0-9] matches small or capital alphabets and numbers.

(): make a group of a match, ([a-zA-Z1-9]) make a group of it to use it later in the solution.

and _ obviously matches underscore.

$1 and $2 in the replacement string refers to the first and second match group in the regex.