0
Let category = "Baby Dress"

I want it to be trimed by spaces and text into lowercase. the output as "babydress". I used the following code. but it returns "baby dress".

category.trim(" ").toLowerCase()

I need to understand why it is not doing as I expected and what are the ways to do it.

3 Answers 3

5

It's not working as expected because .trim function is used to remove whitespace from both sides of the string, not from in-between.

enter image description here

You can use

category.toLowerCase().split(" ").join("")

Here I'm making the letters lower case, splitting them and then joining them.

Sign up to request clarification or add additional context in comments.

Comments

2

The trim method only removes spaces at the beginning of the string. What you need is replacing the spaces with nothing with the replace method using regex:

category.replace(/\s/g, "").toLowerCase();

2 Comments

Regex is typically slower than the split function.
pretty sure for what he needs the difference is going to be astronomically small :)
2

You can do like this:

category.replace(/\s+/g, '').toLowerCase()

3 Comments

That will only remove the first space.
and \s+ is more efficient
thats true :) in case there were more than one space between words

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.