3

How can I remove a part of each string in an array?

For example, an array like:

["u_img/5/16.png", "u_img/5/17.png", "u_img/5/19.png", "u_img/5/18.png"]

With u_img/5/ removed, the result:

["16.png", "17.png", "19.png", "18.png"]

Appreciate your help.

2 Answers 2

6

I think the Array.map() function should do what you want.

let original = ["u_img/5/16.png", "u_img/5/17.png", "u_img/5/19.png", "u_img/5/18.png"],
  result = original.map(function(d) {
    return d.replace('u_img/5/', '');
  });
console.log(result); //["16.png", "17.png", "19.png", "18.png"]

Sign up to request clarification or add additional context in comments.

4 Comments

i think sub string is better than string replace: var fileNameIndex = d.lastIndexOf("/") + 1; return d.substr(fileNameIndex);
is it like var old_array = ["u_img/5/16.png", "u_img/5/17.png", "u_img/5/19.png", "u_img/5/18.png"]; var result = old_array.map(function(d) { return d.replace('u_img/5/', ''); });
Yes. I used the name "original" where you are using "old_array".
Using shorthand notation, result = original.map(x=>x.replace('match','');
1

One way to do it is to use the each function (since you specified jquery in the tag):

var x = ["u_img/5/16.png", "u_img/5/17.png", "u_img/5/19.png", "u_img/5/18.png"];

$.each(x, function (index, value) {
    x[index] = value.replace("u_img/5/", "");
});

console.log(x);

Comments

Your Answer

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