0

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.

asked Nov 26, 2014 at 12:18
1

5 Answers 5

2

RegEx to replace leading whitespace:

for (var i = 0; i < arr.length; i++)
 arr[i] = arr[i].replace(/^\s+/, "");
answered Nov 26, 2014 at 12:22
Sign up to request clarification or add additional context in comments.

Comments

0

You can try, replace()

strArray[0].replace(/\s/g, "") ;
answered Nov 26, 2014 at 12:22

1 Comment

Second one fails space between X and YZ1 is not deleted
0
for (var i = 0; i < array.length; i++)
array[i] = array[i].trim();
}
answered Nov 26, 2014 at 12:25

1 Comment

trim() removes whitespace from both sides of a string.
0

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());
answered Nov 26, 2014 at 12:27

Comments

0

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>

answered Nov 26, 2014 at 12:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.