How to add a character to the beginning of every word in a string in javascript?
You could map the splitted strings and add the prefix. Then join the array.
var string = "Hello there! How are you?",
result = string.split(' ').map(s => '#0' + s).join(' ');
console.log(result);
You could use the regex (\b\w+\b)
, along with .replace()
to append your string to each new word
\b
matches a word boundry
\w+
matches one or more word characters in your string
$1
in the .replace()
is a backrefence to capture group 1
let string = "Hello there! How are you?";
let regex = /(\b\w+\b)/g;
console.log(string.replace(regex, '#0$1'));
You should use map(), it will directly return a new array :
let result = some_string.split(" ").map((item) => {
return "#0" + item;
}).join(" ");
console.log(result);