Removing Extra Spaces from Strings in Microsoft Jscript
MS Jscript has a ton of functions and methods borrowed from VisualBasic and Microsoft C/C++. Among them is the trim function, which lets you strip extra space characters from the start and end of a string. But what do you do if there are extra spaces between words inside the string?
Here’s a function for you to use as you see fit. The basic idea: split the string and dump it into an array. Then walk through the array elements and build a new string, skipping any array elements that are just spaces. That string gets returned as the result.
We’ll use the split function to create the array.
function TrimInner(Str)
{
var WordArray = Str.split(/ +/);
Str = "";
for (i = 0; i < WordArray.length; i++) {
if (WordArray[i] != ' '){
Str += (WordArray[i]+ " ")
}
};
return Str;
}
Pass it the string you need as an argument, and you get back a string with no extra spaces.
function TrimInner(Str)
{
var WordArray = Str.split(/ +/);
Str = "";
for (i = 0; i < WordArray.length; i++) {
if (WordArray[i] != ' '){
Str += (WordArray[i])
}
};
return Str;
}