Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a string for example

some_string = "Hello there! How are you?"

I want to add a character to the beginning of every word such that the final string looks like

some_string = "#0Hello #0there! #0How #0are #0you?"

So I did something like this

temp_array = []

some_string.split(" ").forEach(function(item, index) {
    temp_array.push("#0" + item)

})

console.log(temp_array.join(" "))

Is there any one liner to do this operation without creating an intermediary temp_array?

like image 495
Souvik Ray Avatar asked Feb 02 '20 18:02

Souvik Ray


4 Answers

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'));
like image 31
Shiny Avatar answered Sep 21 '22 10:09

Shiny


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);
like image 74
Nina Scholz Avatar answered Sep 18 '22 10:09

Nina Scholz


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);
like image 35
SanjiMika Avatar answered Sep 22 '22 10:09

SanjiMika


You could do it with regex:

let some_string = "Hello there! How are you?"

some_string = '#0' + some_string.replace(/\s/g, ' #0');
console.log(some_string);
like image 20
technophyle Avatar answered Sep 22 '22 10:09

technophyle