简体   繁体   English

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

[英]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 ?是否有任何一个班轮在不创建中间temp_array情况下执行此操作?

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\\w+\\b)以及.replace()将您的字符串附加到每个新单词

\\b matches a word boundry \\b匹配单词边界

\\w+ matches one or more word characters in your string \\w+匹配字符串中的一个或多个单词字符

$1 in the .replace() is a backrefence to capture group 1 .replace()中的$1是捕获组 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 :您应该使用map() ,它会直接返回一个新数组:

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.结果是 +floral +print 对 mysql 全文布尔模式搜索很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM