假设我有这一系列的推文:
var arr = ['@userone Hey man, whats popping', 'Shoutout to @usertwo haha']
我如何摆脱提及并仅包含消息?所以喜欢:
var newArr = ['Hey man, whats popping', 'Shoutout to haha']
这是我能想到的
if (tweet.includes('@')) {
var atIndex = tweet.indexOf('@');
var spaceIndex = // index of the nearest space after @
var strToReplace = tweet.substring(atIndex, spaceIndex);
tweet = tweet.replace(strToReplace, '');
}
请帮忙。
答案 0 :(得分:1)
var arr = ['@userone Hey man, whats popping',
'Shoutout to @usertwo haha'
];
var i = 0, at_pos, sp_pos, str_rep;
while(i<arr.length) {
at_pos = arr[i].indexOf('@');
sp_pos = arr[i].indexOf(' ', at_pos);
str_rep = arr[i].substring(at_pos, sp_pos+1);
arr[i] = arr[i].replace(str_rep, '');
console.log(arr[i]);
i++;
}
&#13;
或者只是你可以使用像
这样的正则表达式
var arr = ['@userone Hey man, whats popping',
'Shoutout to @usertwo haha'
];
var i=0;
while(i<arr.length){
arr[i] = arr[i].replace(/\@[^\s]*\s/g, '');
console.log(arr[i]);
i++;
}
&#13;
答案 1 :(得分:1)
arr.map(e => e.replace(/(?:^|\W)@(\w+)(?!\w)/g,"") )
在一行中完成:) ...演示是here
答案 2 :(得分:1)
正则表达式是你的朋友。
var arr = ['@userone Hey man, whats popping', 'Shoutout to @usertwo haha'];
arr.forEach(function(element,index) {
arr[index] = element.replace(/@[A-Za-z0-9]*\s/, "");
}
console.log(arr);
答案 3 :(得分:1)
建立在@Abdennour ...
var newArr = arr.map(e => e.replace(/@\w+\s+/,"") );