[英]JavaScript: How to get index of the occurrence of a certain character that is immediately after another certain character?
Let's say I have this array of tweets: 假设我有以下一系列推文:
var arr = ['@userone Hey man, whats popping', 'Shoutout to @usertwo haha']
How would I make get rid of the mentions and only contain the message? 我如何摆脱提及而只包含消息? So like:
像这样:
var newArr = ['Hey man, whats popping', 'Shoutout to haha']
Here's what I can come up with 这是我能想到的
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, '');
}
Please help. 请帮忙。
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++; }
OR simply you can use regular expressions like 或者简单地,您可以使用正则表达式,例如
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++; }
arr.map(e => e.replace(/(?:^|\W)@(\w+)(?!\w)/g,"") )
一行完成:) ...演示在这里
Regex is your friend here. 正则表达式是您的朋友在这里。
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);
建立在@Abdennour ...
var newArr = arr.map(e => e.replace(/@\w+\s+/,"") );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.