Home > Net >  The difference between "" vs " " Javascript
The difference between "" vs " " Javascript

Time:04-30

I used this to remove white spaces from a string.

returnString.split(" ").filter(substr => substr !== "");

In my head it should be this:

returnString.split(" ").filter(substr => substr !== " ")    //note the space between the " "

why doesnt the bottom one work? Is it JS sytax?

Answer: If theres a space at the beginning of the string, its split with an empty string, (so substr !== "") removes that from the returned array when splitting the string.

CodePudding user response:

returnString.replace(/\s/g,'') Would be a superior way of doing this.

"" is an empty string.

" " is a space character.

They cannot be used interchangeably.

CodePudding user response:

"" is an empty string

so if theres a space at the beginning of the string, it will split that space with an empty string

so thats why substr !== "" is needed to remove the empty string.

CodePudding user response:

As mentioned in the comments, you’re splitting on whitespaces, creating indices for said whitespaces.

const returnString = 'Hello I am Victor'

const str = returnString.split("").filter(substr => substr !== " ");

console.log(str.join(''))

would get you the desired result.

However, a regex pattern would be best suitable for this use case.

returnString.replace(/\s/g, '')
  • Related