简体   繁体   English

JavaScript:如何获取紧接在另一个特定字符之后的某个特定字符的出现索引?

[英]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.

相关问题 最后一次出现某个字符后,如何在url中获取参数 - How to get parameters in an url after last occurrence of a certain character 如何使用JavaScript(html)删除某个字符出现之前/之后的所有内容 - How to remove everything before/after the occurrence of a certain character using JavaScript (html) 如何通过Javascript检测某个字符之后是否有任何内容? - How to detect if there are anything after a certain character by Javascript? 如何检查字符串中的某个字符是否在另一个字符之后? - How to check whether a certain character in string comes after another character? 在特定索引后找到indexOf字符 - Find indexOf character after certain index 如何使用 javascript 在第 9 次出现字符后获取文本? - How to get text after the 9th occurrence of a character using javascript? 在某个字符之后选择1个字符 - Select 1 character after a certain character 如何使用javascript或jquery隐藏某个字符后的字符串结尾 - How to hide the end of a string after a certain character, with javascript or jquery 如何使用 javascript 在某个字符后换行标题 - How To Break line the Title after a certain character using javascript 在某些字符javascript之后将元素添加到数组中 - Adding to elements to an array after a certain character javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM