0

I have a string that I want to do a process to it:

1) split it by '.' and make an array

2) make each word and character to lower case

3) trim the array elements

I know that we can do this by coding each step separately but I want to do this in one line. But it confused me why I can't do this using map(s => s.toLowerCase() && s.trim()) only the last method in the map works?

Any suggestions would be greatly appreciated.

let trapSt = '  I Was Sent = I Sent. To Earth = To Moon     '
trapSt = trapSt.split(".")
only_LowerCase_Works_Here = trapSt.map(s => s.trim() && s.toLowerCase()); // ??? why only s.toLowerCase() works here???!!!!
only_Trim_Works_Here = trapSt.map(s => s.toLowerCase() && s.trim()); // ??? why only s.trim() works here???!!!!

console.log(only_LowerCase_Works_Here); 
console.log(only_Trim_Works_Here); 

1
  • 1
    strings are immutable. You could chain the methods s.toLowerCase().trim() or you could simply use toLowerCase on the original string before doing the split. Commented Nov 5, 2019 at 20:17

1 Answer 1

1

Because toLowerCase and trim don't modify the string in place, they return the string after the modification.

The && isn't the same as:

s.toLowerCase().trim()

which is what you want.

Try this:

let trapSt = '  I Was Sent = I Sent. To Earth = To Moon     '
trapSt = trapSt.split(".")
only_LowerCase_Works_Here = trapSt.map(s => s.trim() && s.toLowerCase()); // ??? why only s.toLowerCase() works here???!!!!
only_Trim_Works_Here = trapSt.map(s => s.toLowerCase().trim()); // ??? why only s.trim() works here???!!!!

console.log(only_LowerCase_Works_Here); 
console.log(only_Trim_Works_Here); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer ... plus one... Actually I'm surprised how it worked... I remember toLowerCase().trim() resulted in errors before! that was why I used &&...
Not a problem, and thanks! If the "string" in question is null or undefined, you will get errors. Other than that, any valid string should be able to go through .toLowerCase().trim()

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.