1

I need to sanitise strings of names (which may contain special characters) so that they are url friendly. For example a name may be:

The Red Hot Chili Peppers
A$AP Rocky
Christine & The Queens
Will.I.Am

These should be:

the-red-hot-chili-peppers
asap-rocky
christine-and-the-queens
will-i-am

Also other special characters like exclamation marks, slashes, dashes etc should be removed.

Is there a node module I can use to do this? How should I attempt this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Tometoyou
  • 7,792
  • 12
  • 62
  • 108
  • 1
    Possible duplicate of [How to convert a Title to a URL slug in jQuery?](https://stackoverflow.com/questions/1053902/how-to-convert-a-title-to-a-url-slug-in-jquery) – Michael Feb 06 '19 at 14:13
  • 1
    In the code example you replaced `.` and spaces with dashes and then write "dashes should be removed". – chrisg86 Feb 06 '19 at 14:17
  • 1
    Your example implies that "$" should be converted to uppercase "S", "&" to "and", period and single space to dash. But the answerer shouldn't have to compare your before-and-after example to extract the requirements; you should explicitly state them. – Richard II Feb 06 '19 at 14:44

1 Answers1

2

const str = `The Red Hot Chili Peppers
A$AP Rocky
Christine & The Queens
Will.I.Am`;

const result =
  str
  .split("\n")
  .map(el => el
    .toLowerCase()
    .replace(/[$]|[ & ]+|[.]+|[ ]+/gi, x => x === '$' ? 's' : '-'))
  .join("\n");


console.log(result);
Aziz.G
  • 3,599
  • 2
  • 17
  • 35
  • 1
    final .join should be .join("\n") instead of .join("-"). I couldn't edit because the change is less than 6 characters. – Richard II Feb 06 '19 at 14:35
  • it depends i think he what a string for an url so with .join("-") do the job he can changed it – Aziz.G Feb 06 '19 at 14:37
  • 1
    OP's example *output* retained newlines from the *input*. OP's requirements were vague, so you have to read between the lines (pun intended) – Richard II Feb 06 '19 at 14:46