I’m working on regex (regexes, actually) that will satisfy my needs. 🙂
I need to replace given string (named title) and return slug:
-
Replace one white-space with one underscore in places where are one white-space. If there are more then one white-space, only one white-space should be replaced. It’s hard to explain, but I will try to explain with example.
Hi and hello, world!would beHi_and_hello,_world!, but if there would be, for example, two white-spaces before ‘world’, it would beHi_and_hello,_ world!, -
Replace all remaining white-spaces with nothing (
''), -
Replace all unwanted characters (white-list:
a-z,A-Z,0-9and underscore). In other words, if symbol isn’t in the white-list, it should be replaced with nothing (''), -
Trim beginning and end from underscores;
The end result should be:
Hello, world! I'm known as daGrevis. :)
…to:
Hello_world_Im_known_as_daGrevis
All that stuff I need to do in the JavaScript. This is what I got so far:
slug = title.replace(/\s+/g, '_');
slug = title.replace(/\s+/g, '');
slug = title.replace(/[^\w0-9a-zA-Z]/g, '');
I’m not good with regexies so don’t laugh on me. 😀 Thanks in an advice!
In other words:
There you go:
\s+matches as much consecutive whitespace (space, newline, tab, ..) as possible/gis a global flag, means: “select every match”/[^a-z0-9_]/gimeans: Anything which is not an alphanumeric character or underscore, case insensitive^and$are markers for the beginning and end of a string.^_+|_+$/gmeans: match every underscore at the beginning and end of a stringDon’t forget to perform the following replacements on
slug, instead oftitle. Otherwise, you “forget” your previous replacements.