admin管理员组

文章数量:1202361

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?

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?

Share Improve this question asked Feb 2, 2020 at 18:12 Souvik RaySouvik Ray 3,0187 gold badges44 silver badges81 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 10

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);

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);

The simplest solution is regex. There is already regex soln give. However can be simplified.

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

console.log(some_string.replace(/[^\s]+/g, m => `#0${m}`))

const src = "floral print";
const res = src.replace(/\b([^\s]+)\b/g, '+$1');

result is +floral +print useful for mysql fulltext boolean mode search.

本文标签: How to add a character to the beginning of every word in a string in javascriptStack Overflow