Strip everything but letters and numbers and replace spaces that are in the sentence with hyphens

Viewed 2456

So I'm trying to parse a string similar to the way StackOverflow's tags work. So letters and numbers are allowed, but everything else should be stripped. Also spaces should be replaced with hyphens, but only if they are inside the word and not have disallowed characters before them.

This is what I have right now:

label = label.trim();
label = label.toLowerCase();
label = label.replace(/[^A-Za-z0-9\s]/g,'');
label = label.replace(/ /g, '-');

This works but with a few caveats, for example this:

 / this. is-a %&&66 test tag    .   <-- (4 spaces here, the arrow and this text is not part of the test string)

Becomes:

-this-is-a66-test-tag----

Expected:

this-is-a66-test-tag

I looked at this to get what I have now:

How to remove everything but letters, numbers, space, exclamation and question mark from string?

But like I said it doesn't fully give me what I'm looking for.

How do I tweak my code to give me what I want?

2 Answers

You need to make 2 changes:

  • Since you do not replace all whitespace with the first replace you need to replace all whitespace chars with the second regex (so, a plain space must be replaced with \s, and even better, with \s+ to replace multiple consecutive occurrences),
  • To get rid of leading/trailing hyphens in the end, use trim() after the first replace.

So, the actual fix will look like

var label = " / this. is-a %&&66 test tag    .   ";
label = label.replace(/[^a-z0-9\s-]/ig,'')
  .trim()
  .replace(/\s+/g, '-')
  .toLowerCase();
console.log(label); // => this-isa-66-test-tag

Note that if you add - to the first regex, /[^a-z0-9\s-]/ig, you will also keep the original hyphens in the output and it will look like this-is-a-66-test-tag for the current test case.

Use trim just before changing all spaces with hyphens.

You can use this function:

function tagit(label) {
label = label.toLowerCase().replace(/[^A-Za-z0-9\s]/g,'');
return label.trim().replace(/ /g, '-'); }

var str = 'this. is-a %&&66 test tag    .'

console.log(tagit(str));
//=> "this-isa-66-test-tag"

Related