valzavagoth
valzavagoth

Reputation: 31

placing dashes in a string

function dashes(str) {
    str =  str.replace(/_/g,' ').replace(/\s+/g,"-").toLowerCase();
    return str;
}

//test cases
dashes("thisCakeIsDelicious");
dashes("TheBig cat was Boastful");

the desired output respectively are: "this-cake-is-delicious" and "the-big-cat-was-boastful". How do i put a space between "TheBig" without contradicting the space before "Boastful". I have tried regex particular capital letters but as you can see Big and Boastful start with B.

Upvotes: 1

Views: 94

Answers (3)

adeneo
adeneo

Reputation: 318162

You could use a callback in the replace function

function dashes(str) {
    return str.replace(/(?!^)(\s?[A-Z\s+])/g, function(x) {
    	return '-' + x.trim();
    }).toLowerCase();
}

//test cases
console.log( dashes("thisCakeIsDelicious") );
console.log( dashes("TheBig cat was Boastful") );

Upvotes: 0

Marcs
Marcs

Reputation: 3838

This should work, but I'm not absolutely sure about the requirements so I decided to divide by word not by letter (so LLLLie will result in llllie, not l-l-l-lie)

([a-z]+)([A-Z]{1})|(\s)

Matches:

  • ([a-z]+): 1 or more lowercase letter
  • ([A-Z]{1}): 1 uppercase letter
  • (\s+): one or more whitespace character (equal to [\r\n\t\f\v ])

var dasher = function(str) {
  return str
         .trim()
         .replace(/([a-z]+)([A-Z]{1})|(\s+)/g, '$1-$2')
         .toLowerCase();
}

console.log(dasher('thisCakeIsDelicious'));
console.log(dasher('TheBig cat was Boastful'));
console.log(dasher('The cakeIsA     LLLLLie'));
console.log(dasher('  JeremySpoke inClass  Today'));

Upvotes: 3

dhaninugraha
dhaninugraha

Reputation: 9

x = "thisCakeIsDelicious";
x.replace(/([a-z](?=[A-Z]))| /g, '$1-');

results in

this-Cake-Is-Delicious,

and

x = "TheBig cat was Boastful";
x.replace(/([a-z](?=[A-Z]))| /g, '$1-');

results in

The-Big-cat-was-Boastful

Upvotes: 0

Related Questions