- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript function to prepend string into all the values of array?
Suppose, we have an array of string literals like this −
const arr = ["a", "b", "c"];
What we want is that we have a string that let say "Hello" and we want to prepend this string to each and every value of the array.
Therefore, our function should take one array of strings as the first argument and a single string as the second argument.
Then the function should prepend the second argument string to each element of the array.
We should also insert a separator ("_" in our case) between the two values.
Therefore, our output should look like −
const output = ["Hello_a", "Hello_b", "Hello_c"];
Example
The code for this will be −
const arr = ["a", "b", "c"]; const prependLiteral = (arr = [], str = '') => { for(let i = 0; i < arr.length; i++){ arr[i] = `${str}_` + arr[i]; }; return arr.length; }; prependLiteral(arr, 'Hello'); console.log(arr);
Output
And the output in the console will be −
[ 'Hello_a', 'Hello_b', 'Hello_c' ]
- Related Articles
- Summing all the unique values of an array - JavaScript
- How to convert an array into JavaScript string?
- All ways to divide array of strings into parts in JavaScript
- How to turn a String into a JavaScript function call?
- Join Map values into a single string with JavaScript?
- How to prepend string to entire column in MongoDB?
- How to get all unique values in a JavaScript array?
- PHP program to split a given comma delimited string into an array of values
- JavaScript function that generates all possible combinations of a string
- Sum all duplicate values in array in JavaScript
- How to filter values from an array using the comparator function in JavaScript?
- JavaScript: Combine highest key values of multiple arrays into a single array
- How to prepend a string to a column value in MySQL?
- How to get the numbers which can divide all values in an array - JavaScript
- Return a splitted array of the string based on all the specified separators - JavaScript

Advertisements