Mohan Mohan - 6 months ago 15
Javascript Question

How to concanicate string to an array item which is also of type string in JavaScript

I have an array of strings

var originalText = [
"Sample Text",
"More Text"
];

var extraString = "extra text to be appended";


I want to concatenate extraString to each of the entry in originalText, so final output is

originalText = [
"Sample Text extra text to be appended",
"More Text extra text to be appended"
]

Answer

You can use Array#forEach() and append every element with the wanted string.

var originalText = [
    "Sample Text",
    "More Text"
];

var extraString = "extra text to be appended";

originalText.forEach(function(_, i, aa) {
    aa[i] += ' ' + extraString;
});

console.log(originalText);