如何在JavaScript中的字符串的每个单词前添加一个字符?

8

我有一个字符串,例如:

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个回答

9
你可以映射分割后的字符串并添加前缀,然后将数组拼接起来。

var string = "Hello there! How are you?",
    result = string.split(' ').map(s => '#0' + s).join(' ');

console.log(result);


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
您应该使用map()方法,它会直接返回一个新的数组 :
let result = some_string.split(" ").map((item) => {
    return "#0" + item;
}).join(" ");

console.log(result);

1
你可以使用正则表达式来实现它:

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

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


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

结果是 +花卉 +印花 在 MySQL 全文布尔模式搜索中非常有用。


0

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

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接