这是我的字符串:
var str1 = '@hello, world how are you. I @am good';
现在我想将@
前缀世界(如@hello,@ am等)分割成一个数组。
期望的输出将是
var str2 = [@hello, @am];
任何人都可以指导我。
答案 0 :(得分:1)
使用简单的正则表达式
\B@\w+/g
没有功能:
var str1 = '@hello, world how are you. I @am good';
console.log(str1.match(/\B@\w+/g));
有一个功能:
getMatchedStrings("@hello, #world how are you. I @am good");
function getMatchedStrings(input){
var re = /\B@\w+/g;
var specials = [];
var match;
while(match = re.exec(input)){
specials.push(match[0]);
}
console.log(specials)
}
你可以在这里尝试更多正则表达式:
https://regex101.com/r/rBuMrY/1
输出:
["@hello", "@am"]
答案 1 :(得分:0)
var str1 = '@hello, world how are you. I @am good';
var reg = /(?:^|[ ])@([a-zA-Z]+)/;
var str = str1.split(" ");
//console.log(str.length);
for (var i = 0; i < str.length; i++) {
if (reg.test(str[i])) {
//your code to store match value in another array
console.log(str[i]);
}
}
&#13;
答案 2 :(得分:0)
使用正则表达式,我不是很擅长但只是尝试
var str1 = '@hello, world how are you. I @am good';
var str2 = str1.match(/@(.+?)[^a-zA-Z0-9]/g).map(function(match) { return match.slice(0, -1); });
console.log(str2);
&#13;
答案 3 :(得分:0)
检查一下,我添加评论以便于理解此代码
var str = '@hello, world how are you. I @am good';
str = str.split(' '); // split text to word array
str = str.filter(function(word){
return word.includes('@'); // check words that using @
}).map(function (word) {
return word.replace(/[^a-zA-Z^@ ]/g, "") // remove special character except @
});
console.log(str) // show the data
&#13;