How to add a character to the beginning of every word in a string in JavaScript?

We need to write a function that takes two strings and returns a new string with the second argument prepended to every word of the first string.

For example:

Input ? 'hello stranger, how are you', '@@'
Output ? '@@hello @@stranger, @@how @@are @@you'

If the second argument is not provided, we'll use '#' as the default character.

Solution Using split() and map()

The most straightforward approach is to split the string into words, prepend the character to each word, and join them back:

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'));
console.log(prependString(str, '@@'));
#hello #stranger, #how #are #you
43hello 43stranger, 43how 43are 43you
@@hello @@stranger, @@how @@are @@you

How It Works

The solution works in three steps:

  1. split(" ") - Splits the string into an array of words using space as delimiter
  2. map() - Transforms each word by prepending the specified character
  3. join(" ") - Combines the modified words back into a single string

Alternative Using Regular Expression

For a more concise solution, we can use regular expressions to replace word boundaries:

const prependWithRegex = (str, text = '#') => {
    return str.replace(/\b\w/g, match => text + match);
};

const str = 'hello stranger, how are you';
console.log(prependWithRegex(str));
console.log(prependWithRegex(str, '@@'));
#hello #stranger, #how #are #you
@@hello @@stranger, @@how @@are @@you

Comparison

Method Readability Performance Handles Punctuation
split/map/join High Good Punctuation stays with words
Regular Expression Medium Better Separates words from punctuation

Conclusion

The split/map/join approach is more readable and easier to understand. Use regular expressions when you need more precise word boundary detection or better performance with large strings.

Updated on: 2026-03-15T23:18:59+05:30

951 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements