如何在javascript字符串中的每个单词的开头添加字符?

时间:2020-02-02 18:12:03

标签: javascript string

例如,我有一个字符串

some_string = "Hello there! How are you?"

我想在每个单词的开头添加一个字符,以使最终字符串看起来像

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

所以我做了这样的事情

temp_array = []

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

})

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

在不创建中介temp_array的情况下,是否有任何班轮人员可以执行此操作?

6 个答案:

答案 0 :(得分:5)

您可以映射拆分的字符串并添加前缀。然后加入数组。

return false

答案 1 :(得分:5)

您可以使用正则表达式(\b\w+\b).replace()来将字符串附加到每个新单词

\b与单词边界匹配

\w+匹配字符串中的一个或多个单词字符

$1中的

.replace()是捕获第1组的反向引用

let string = "Hello there! How are you?";
let regex = /(\b\w+\b)/g;

console.log(string.replace(regex, '#0$1'));

答案 2 :(得分:2)

您应该使用 map(),它将直接返回一个新数组:

let result = some_string.split(" ").map((item) => {
    return "#0" + item;
}).join(" ");

console.log(result);

答案 3 :(得分:1)

您可以使用正则表达式:

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

some_string = '#0' + some_string.replace(/\s/g, ' #0');
console.log(some_string);

答案 4 :(得分:0)

最简单的解决方案是regex。已经有正则表达式给。但是可以简化。

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

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

答案 5 :(得分:0)

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

结果是+花卉+印花 对mysql全文布尔模式搜索很有用。