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
?
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 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 should use map(), it will directly return a new array :
let result = some_string.split(" ").map((item) => {
return "#0" + item;
}).join(" ");
console.log(result);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With