Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

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
Updated on: 2020-08-20T06:17:16+05:30

859 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements