I have the following Array in JavaScript:
["X1", " X2", " X3", " X4", " X5", " X6", " X YZ1", " X YZ2", " X7", " X8", " X9"]
I would like to delete the empty spaces before a letter is beginning, see for example X2. But I would like that the space between X and YZ1 is not deleted.
Does anybody know, how I can do that?
Thank you in advance.
Greets.
-
1developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Abhitalks– Abhitalks2014年11月26日 12:21:24 +00:00Commented Nov 26, 2014 at 12:21
5 Answers 5
RegEx to replace leading whitespace:
for (var i = 0; i < arr.length; i++)
arr[i] = arr[i].replace(/^\s+/, "");
Comments
You can try, replace()
strArray[0].replace(/\s/g, "") ;
1 Comment
space between X and YZ1 is not deletedfor (var i = 0; i < array.length; i++)
array[i] = array[i].trim();
}
1 Comment
here is working solution, that adds a new method to Array object.
Demo: http://jsfiddle.net/bnpeon25/
a = ["X1", " X2", " X3", " X4", " X5", " X6", " X YZ1", " X YZ2", " X7", " X8", " X9"];
Array.prototype.trimvals = function() {
for (var i = 0; i < this.length; i++) {
this[i] = this[i].replace(/^\s+/, "");
}
return this;
}
console.log(a.trimvals());
Comments
All modern browsers natively support .trim(). Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
arr[i] = arr[i].trim();
This will not delete the embedded spaces as you stated in your question.
Alternatively, if you want to get rid of all spaces: leading, trailing and embedded; then you could you regex:
arr[i] = arr[i].replace(/\s/g, "");
Snippet using .trim() (Leading and Trailing Spaces):
var arr = ["X1", " X2", " X3", " X4", " X5", " X6", " X YZ1", " X YZ2", " X7", " X8", " X9"];
for (var i = 0; i < arr.length; i++) { arr[i] = arr[i].trim(); }
document.getElementById("result").innerText = arr.join(",");
<p id="result"></p>
Snippet using regex (Simple all spaces):
var arr = ["X1", " X2", " X3", " X4", " X5", " X6", " X YZ1", " X YZ2", " X7", " X8", " X9"];
for (var i = 0; i < arr.length; i++) { arr[i] = arr[i].replace(/\s/g, ""); }
document.getElementById("result").innerText = arr.join(",");
<p id="result"></p>