Click here to Skip to main content
14,970,653 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need a regex - well, two:
I want a JS regex to replace all whitespace with a hyphen
JavaScript
var str = 'some string';
var regex1 = ?????;
str = str.replace(regex1, '-');
and another to replace all non-alphanumerics with nothing - ie remove them
JavaScript
regex2 = ?????;
str = str.replace(regex2, '');


What I have tried:

Banging my head against a brick wall.
Wearing a garlic necklace.
I am armed with a wooden stake and a gun with a silver bullet.
Posted
Updated 4-Feb-18 1:05am
v2

1 solution

All whitespace: /\s/g
All non-alphanumerics: /[^a-zA-Z0-9]/g
   
Comments
A_Griffin 4-Feb-18 6:21am
   
Thanks! Well, I knew it was easy .... I just have a mental block against regex.... cannot get my head around it.

Of course.... what I actually need is to exclude hyphens form the second one...
A_Griffin 4-Feb-18 6:22am
   
Hey - I figured that (hyphen thing) - I'm a genius!!!! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900