Skip to content

Instantly share code, notes, and snippets.

@masautt
Created September 16, 2019 05:22
Show Gist options
  • Save masautt/9fd6d671232ced7a6dcebfd417e155f2 to your computer and use it in GitHub Desktop.
Save masautt/9fd6d671232ced7a6dcebfd417e155f2 to your computer and use it in GitHub Desktop.
How to remove whitespace from a string in JavaScript?
// Remove all whitespace
function delWS1(str) {
return str.replace(/\s/g,"");
}
// Remove trailing and leading whitepsace
function delWS2(str) {
return str.replace(/^[ ]+|[ ]+$/g,'');
}
// Remove trailing and leading whitepsace with built in prototype trim
function delWS3(str) {
return str.trim();
}
console.log(delWS1("! Hello World !")) // --> "!HelloWorld!"
console.log(delWS2(" Hello World ")) // --> "Hello World"
console.log(delWS3(" Hello World ")) // --> "Hello World"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment