Replace text only when occuring between specific characters

42 views Asked by At

I have a string like this:

- - This is the place where the people like to join think-tanks and have fun.

I can obviously replace all hyphens with a space using either:

my_string.replace(/-/g, ' ')

my_string.split('-').join(' ')

I need to replace only the hyphen in think-tank with a space. The other hyphens can be left alone.

How can I target only the hyphen between letters within a string?

1

There are 1 answers

0
Terry On BEST ANSWER

Just capture the letters using \w, and then replace the dash with a space"

str.replace(/(\w)\-(\w)/gi, '$1 $2')

The word metacharacter is a shorthand for [0-9a-zA-Z_], i.e. including digits, upper/lowercase alphabets and underscore.

const str = '- - This is the place where the people like to join think-tanks and have fun.';

console.log(str.replace(/(\w)\-(\w)/gi, '$1 $2'));