0

I want to convert my string(str) to spinal-case string. Please explain me that how regex is working differently. Upper line of code is working properly but another line of code is putting "-" many times.

str.split(/\s|(?=[A-Z])|_/g).join("-").toLowerCase();
// or
str.replace(/\s|(?=[A-Z])|_/g,"-").toLowerCase();
Sagar
  • 3
  • 3
  • 3
    You should include the original string that you're attempting to change; how can anybody tell what you're trying to do otherwise? – Pointy Jun 16 '21 at 03:24

1 Answers1

0

The code is searching for any blank space and replacing it with a dash. (this is due to the \s in your code). So, for example if it finds 3 whitespaces one after the other, then it's going to replace them with 3 dashes.

You correct this by telling it to search for any groups of one or more blank spaces, such as in the example below:

str.split(/\s{1,}|(?=[A-Z])|_/g).join("-").toLowerCase();

Also, the code can be greatly simplified by just looking for any non-alphanumeric character.

str.split(/\W{1,}/g).join("-").toLowerCase();
Adrian Gh.
  • 59
  • 1
  • 2