skip to Main Content

written this string to match all the test strings at once.

String="AQuickBrown_fox jump over the-lazy-Dog";

Basically I want to make these string look like this:

"a-quick-brown-fox-jump-over-the-lazy-dog"

I tried split("/regex/") function on string and applied join("-") function on the returned array and applied .toLowerCase. But I could not find the solution. I want to know the regular expression that could split the word so that i can get the required string.

3

Answers


  1. From https://www.geeksforgeeks.org/how-to-convert-a-string-into-kebab-case-using-javascript/

    This checks for space, capital letters, and underscores. It creates an array and pushes the words that separate the strings. Now join the array with the hyphen using the join(). After that convert the whole string into a lower case.

    const kebabCase = str => str
        .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
        .join('-')
        .toLowerCase();
    
    console.log(kebabCase('Geeks For Geeks'));
    console.log(kebabCase('GeeksForGeeks'));
    console.log(kebabCase('Geeks_For_Geeks'));
    console.log(kebabCase('AQuickBrown_fox jump over the-lazy-Dog'));
    Login or Signup to reply.
  2. I prefer more than one replace for readability

    I will purloin the kebabCase name for this

    const kebabCase = (str) => str
        // Camelcase - handle single letters too
        .replace(/([a-z])([A-Z])|([A-Z])([A-Z][a-z])/g, '$1$3-$2$4') 
        // non-alphanumeric characters and spaces
        .replace(/[^a-z0-9]+/gi, '-')
        // lowercase and trim dashes
        .toLowerCase().replace(/^-|-$/g, '');
    
    
    const inputString = "AQuickBrown_fox jump over the-lazy-Dog";
    const outputString = kebabCase(inputString);
    console.log(outputString);  // "a-quick-brown-fox-jump-over-the-lazy-dog"
    Login or Signup to reply.
  3. Here’s a solution using replace function:

    const toKebab = text => text.replace(/[W_]+|(?<=[A-z])(?=[A-Z])/g, '-').toLowerCase();
    
    console.log(toKebab('AQuickBrown_fox jump over the-lazy-Dog'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search