javascriptarraysprefix

Add a prefix to all values in an array which don't already have it


I have a JavaScript array:

var arr = ["images/1.jpg", "2.jpg", "some.jpg"];

I want to add the prefix images/ to all items missing it, so that the values that already had the prefix aren't changed.

It should result in this:

var newArr = ["images/1.jpg", "images/2.jpg", "images/some.jpg"];

Solution

  • You can use String.prototype.startsWith() to only add the prefix if it isn't already these.

    In the example below I used Array.prototype.map() and String.prototype.startsWith() to only add a prefix if it's not already there.

    const magic = (arr, prefix) => arr 
      .map(str => str.startsWith(prefix) ? str : `${prefix}${str}`)
    
    console.log(magic(["images/1.jpg", "2.jpg", "some.jpg"], 'images/'))