Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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:
- split(" ") - Splits the string into an array of words using space as delimiter
- map() - Transforms each word by prepending the specified character
- 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.
Advertisements
