Reputation: 991
I have string. I just want to remove all white spaces between all characters.Please reply "PB 10 CV 2662" to "PB10CV2662"
Upvotes: 34
Views: 114458
Reputation: 11
let 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.
Upvotes: 1
Reputation: 987
should not allowed to add space in the end or in between use
replaceAll(' ', '') instead of trim()
.
onChangeText={value => onChange(value.replaceAll(' ', ''))}
Upvotes: 0
Reputation: 10662
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.
Upvotes: 5
Reputation: 131
let text = "space is short but tab is long"
let arr = text.split(" ").filter(x => x !== "")
let finalText = "";
for (let item of arr) {
finalText += item + " "
}
console.log(finalText)
Upvotes: 1
Reputation: 5072
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("")
Upvotes: 7
Reputation: 131
Try this:
var s = "PB 10 CV 2662";
s.replace(/\s+/g, '');
OR
s.replace(/\s/g, '');
Upvotes: 13
Reputation: 2068
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.
Upvotes: 0
Reputation: 2431
var str = "PB 10 CV 2662";
var cleaned = str.replace(/\s+/g, "");
Upvotes: 2
Reputation: 7940
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.
Upvotes: 2
Reputation: 27802
This should do the trick:
var str = "PB 10 CV 2662";
str = str.replace(/ +/g, "");
Upvotes: 79