Reputation: 169
Can anyone help me with replacing this string into desired url link please?
1080 Center - (previously) Old/New
to
1080-center-previously-old-new
Upvotes: 1
Views: 532
Reputation: 5491
This will solve your single example (regex's shamelessly stolen from Rails' parameterize
method:
"1080 Center - (previously)".toLowerCase().replace(/[^a-z0-9\-_]+/g, "-").replace(/-{2,}/, "-").replace(/^-|-$/, '');
But it's hard to come up with a generalized solution without more example input and output.
That being said, you'll probably have an easier time if you come up with a precise specification for what you want to accomplish. For instance, at first it looks like the rule might be "Replace all non-word characters with dashes", but that would turn Center - (previously)
into center----previously-
which is not what you want. On the other hand, you can't just strip out whitespace, as that will lose the separation between 1080
and Center
.
Upvotes: 1
Reputation: 337590
To achieve this you can replace any non-word character with a -
using a Regular Expression. Try this:
var input = '1080 Center - (previously) Old/New';
var output = input.replace(/\W+/g, '-').toLowerCase();
console.log(output);
Upvotes: 0