0

How do you combine eliminating white-spaces and special characters with only a single '-' character? Here's a little Background: When publishing a job to my career section for my company, the ATS will turn a job title for the URL, e.g if a job title is:
Olympia, WA: SLP Full or Part Time it will become olympia-wa-slp-full-or-part-time

I've experimented from other similar questions, but have only come close with this bit of code:

function newTitle(str) {
var x = str.replace(/[\W]/g, '-').toLowerCase();
return x;

now if I run it, the output generated is olympia--wa--slp-full-or-part-time (has 2 dashes from the extra spaces). What am I not getting right?

I've tried the other following bits:

str.replace(/\s+/g, ''); 

and

str.replaceAll("[^a-zA-Z]+", " ");

but neither get close to the desired format.

Thanks!

Brendan
  • 3
  • 1

3 Answers3

0

You got pretty close in your first example, just add + after [\W] to match one or more non-word characters. You can also give it a try in Regexr

function newTitle(str) {
  var x = str.replace(/[\W]+/g, '-').toLowerCase();
  return x;
}

alert(newTitle('Olympia, WA: SLP Full or Part Time'));
Thum Choon Tat
  • 2,601
  • 1
  • 17
  • 20
0

What you actually want, it looks like, is to create a slug from a string.
Here is a nice reusable function that also takes care of multiple dashes:

function slugify(s) {
  s = s.replace(/[^\w\s-]/g, '').trim().toLowerCase();
  s = s.replace(/[-\s]+/g, '-');
  return s;
}

console.log(
  slugify("Olympia, WA: SLP Full or Part Time")
);
wp78de
  • 16,078
  • 6
  • 34
  • 56
0

Your last example [^a-zA-Z]+ almost works if you use a dash as the replacement. This uses a negated character class to match not what you specified so that would include whitespaces and special characters.

Note that if you have a job with for example a digit or an underscore that that would also be replaced. Your could expand the character class with what you don't want to be replaced like [^a-zA-Z0-9]+ or if you also want to keep the underscore \W+ as that would match [^a-zA-Z0-9_]

function newTitle(str) {
  return str.replace(/[^a-zA-Z]+/g, '-').toLowerCase();
}
console.log(newTitle("Olympia, WA: SLP Full or Part Time"));
The fourth bird
  • 96,715
  • 14
  • 35
  • 52