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
?
6 Answers
Reset to default 10You 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
版权声明:本文标题:How to add a character to the beginning of every word in a string in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738651085a2104875.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论