Skip to content Skip to sidebar Skip to footer

Strip Everything But Letters And Numbers And Replace Spaces That Are In The Sentence With Hyphens

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 repl

Solution 1:

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.

Solution 2:

Use trim just before changing all spaces with hyphens.

You can use this function:

functiontagit(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"

Post a Comment for "Strip Everything But Letters And Numbers And Replace Spaces That Are In The Sentence With Hyphens"