Thomas Degroot
Thomas Degroot

Reputation: 524

How do I add text to each text value in a Javascript Array?

I am receiving in my App an Array of text from a backend I have no control over

Array

this.Array = ["/tms/open-attachment/121", "/tms/open-attachment/122"]

I am trying to add "some text added here" to the beginning

this.Array =  ["some text added here/tms/open-attachment/121", "some text added here/tms/open-attachment/122"]

Using

for (let m = 0; m <this.Array.length; m++) { 

}

I have been able to add to the end of the text but not the front.

Is there an easy way to add some custom text to the beginning of the string?

Upvotes: 1

Views: 282

Answers (2)

Chevalmuscl&#233;
Chevalmuscl&#233;

Reputation: 11

If you want to use a traditional for loop:

for (let i = 0; i < array.length; i++) { 
    array[i] = "some text" + array[i];
}

Or, as said CertainPerformance, you can use a Array.prototype.map():

array = array.map(str => "some text" + str)

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371193

Use .map and concatenate what you need:

const arr = ["/tms/open-attachment/121", "/tms/open-attachment/122"];
const result = arr.map(str => 'some text added here' + str);
console.log(result);

Upvotes: 4

Related Questions