I have string. I just want to remove all white spaces between all characters.Please reply "PB 10 CV 2662" to "PB10CV2662"
11 Answers
Try this:
var s = "PB 10 CV 2662";
s.replace(/\s+/g, '');
OR
s.replace(/\s/g, '');
4 Comments
var str = "PB 10 CV 2662";
str = str.split(" ") //[ 'PB', '10', 'CV', '2662' ]
str = str.join("") // 'PB10CV2662'
OR in one line:
str = str.split(" ").join("")
1 Comment
2022 - use replaceAll
Most of these answers were done before the replaceAll method was implemented.
Now you can simply do:
let str = "PB 10 CV 2662";
str = str.replaceAll(' ', '');
Which will replace all instances and is much more readable than the regex to make the .replace a global-replace on a target.
The easiest way would be to use the replace() method for strings:
var stringVal = "PB 10 CV 2662";
var newStringVal = stringVal.replace(/ /g, "");
That will take the current string value and create a new one where all of the spaces are replaced by empty strings.
var str = "PB 10 CV 2662";
var cleaned = str.replace(/\s+/g, "");
7 Comments
\s targets more than just spacesI just want to remove all white spaces, so technically this is correct. My first comment was wrong. Although it should use +. Even if the example only has spaces+. My main point was that the target should be \s, not [ ], based solely on the fact that the OP said "all white spaces", even if the example only uses spaces. I'm betting the OP really only needs to target [ ], but who knowsstr.replace() doesn't modify the string in place (strings are immutable)...it returns a new string. So it needs to be assigned to something. And your example used string.replace, but the variable was str, so I just changed that toolet str1="Lorem Ipsum is simply dummy text of the printing and typesetting industry.";
let str1Arr = str1.split(" ");
str1Arr = str1Arr.filter(item => {
if (item !== " ")
return item;
})
str1 = str1Arr.join(" ");
console.log(str1);
We can remove spaces in between the string or template string by splitting the string into array. After that filter out the text element and skip element having space. And Finally, join the array to string with single spaces.
Comments
Try:
var sample_str = "PB 10 CV 2662"
var new_str = sample_str.split(" ").join("")
Or you could use .replace with the global flag like so:
var sample_str = "PB 10 CV 2662"
var new_str = sample_str.replace(" ","","g")
Both will result in new_str being equal to "PB10CV2662". Hope this is of use to you.

str=str.split(" ").join();str=str.split(" ").join();should bestr=str.split(" ").join(''); your version adds comma in between