[英]How to add a character to the beginning of every word in a string in javascript?
例如,我有一个字符串
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
情况下执行此操作?
您可以映射拆分的字符串并添加前缀。 然后加入数组。
var string = "Hello there! How are you?", result = string.split(' ').map(s => '#0' + s).join(' '); console.log(result);
您可以使用正则表达式(\\b\\w+\\b)
以及.replace()
将您的字符串附加到每个新单词
\\b
匹配单词边界
\\w+
匹配字符串中的一个或多个单词字符
.replace()
中的$1
是捕获组 1 的反向引用
let string = "Hello there! How are you?"; let regex = /(\\b\\w+\\b)/g; console.log(string.replace(regex, '#0$1'));
您应该使用map() ,它会直接返回一个新数组:
let result = some_string.split(" ").map((item) => {
return "#0" + item;
}).join(" ");
console.log(result);
你可以用正则表达式做到这一点:
let some_string = "Hello there! How are you?" some_string = '#0' + some_string.replace(/\\s/g, ' #0'); console.log(some_string);
最简单的解决方案是正则表达式。 已经有正则表达式解决方案。 不过可以简化。
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');
结果是 +floral +print 对 mysql 全文布尔模式搜索很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.