- 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
How to add a character to the beginning of every word in a string in JavaScript?
We are required to write a function that takes in two strings, we have to return a new string which is just the same as the first of the two arguments but have second argument prepended to its every word.
For example −
Input → ‘hello stranger, how are you’, ‘@@’ Output → ‘@@hello @@stranger, @@how @@are @@you’
If second argument is not provided, take ‘#’ as default.
Example
const str = 'hello stranger, how are you'; const prependString = (str, text = '#') => { return str .split(" ") .map(word => `${text}${word}`) .join(" "); }; console.log(prependString(str)); console.log(prependString(str, '43'));
Output
The output in the console will be −
#hello #stranger, #how #are #you 43hello 43stranger, 43how 43are 43you
- Related Articles
- Possible to split a string with separator after every word in JavaScript
- How to add a character before each word in a cell in Excel
- Find word character in a string with JavaScript RegExp?
- How to print the first character of each word in a String in Java?
- Find non-word character in a string with JavaScript RegExp
- Java Program to Capitalize the first character of each word in a String
- Golang program to capitalize first character of each word in a string
- How to count the number of occurrences of a character in a string in JavaScript?
- How to insert a string in beginning of another string in java?
- How to move all capital letters to the beginning of the string in JavaScript?
- How to capitalize the first letter of each word in a string using JavaScript?
- How to get a part of string after a specified character in JavaScript?
- How to add a number and a string in JavaScript?
- Add a character to a specific position in a string using Python
- String function to replace nth occurrence of a character in a string JavaScript

Advertisements