Tsabary
Tsabary

Reputation: 3928

How can I allow hyphens in this RegEx

I know a bit of RegEx but this one's a bit too complicated for me. All I need to change is for it to allow for a single hyphen too.

replace(/[^\p{L}\s]+/gu, '')

Upvotes: 0

Views: 33

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You may use

.replace(/^([^-]*-)|-/g, '$1').replace(/[^\p{L}\s-]+/gu, '')

It will keep the first - in the input string as well as any Unicode letters (\p{L}) and whitespaces (\s), because .replace(/^([^-]*-)|-/g, '$1') will match and capture - from the start of string - all chars other than - up to the first - (with ^([^-]*-)) and then match any other - in the string and replace the matches with the value of Group 1 (it will be empty if the - is not the first hyphen in the string) and .replace(/[^\p{L}\s-]+/gu, '') will remove any one or more chars other than letters, whitespaces and hyphens (there will remain the first one only after the first replacement).

See the ECMAScript 2018+ JS demo below:

console.log( "12-3-**(Виктор Викторович)**...".replace(/^([^-]*-)|-/g, '$1').replace(/[^\p{L}\s-]+/gu, '') )

Upvotes: 1

Related Questions