maimok
maimok

Reputation: 373

Javascript - .replace method not removing whitespace

I'm attempting to use the .replace method to alter my strings of text to remove any special characters, and to replace the white space with a -

For example:

I'd like to alter "Breakfast & Lunch & Dinner " to Breakfast-Lunch-Dinner

I do not want to replace special characters with the - so to speak, but i'd like to replace the white spaces available with -

So for example, if I have another text using the same .replace method such as "Football Basketball Rugby" to return Football-Basketball-Rugby

At the moment I my string is returning with an - but also including the whitespace in between.

Here is a code snippet of my code:

string = 'Breakfast & Lunch & Dinner'

secondString = 'Football Basketball Rugby'


newString = string.replace(/[^a-zA-Z0-9]\s/g, '-');


newSecondString = secondString.replace(/\s+/g, '-')


console.log(newString)

console.log(newSecondString)

Upvotes: 1

Views: 61

Answers (3)

DCR
DCR

Reputation: 15657

string = 'Breakfast & Lunch & Dinner'




newString = string.replace(/[^a-zA-Z0-9]\s/g, '-').replace(/ /g,'');





console.log(newString)

Upvotes: 0

Pavlos Karalis
Pavlos Karalis

Reputation: 2966

just add a + to the array; it already implies \s and can be used for both

newString = string.replace(/[^a-zA-Z0-9]+/g, '-');

string = 'Breakfast & Lunch & Dinner'

secondString = 'Football Basketball Rugby'


newString = string.replace(/[^a-zA-Z0-9]+/g, '-');


newSecondString = secondString.replace(/[^a-zA-Z0-9]+/g, '-')


console.log(newString)

console.log(newSecondString)

Upvotes: 1

dave
dave

Reputation: 64657

You could do this:

string = 'Breakfast & Lunch & Dinner'
newString = string.replace(/([^a-zA-Z0-9]*|\s*)\s/g, '-');
console.log(newString)

Upvotes: 3

Related Questions