【问题标题】:JavaScript: How to get index of the occurrence of a certain character that is immediately after another certain character?JavaScript:如何获取紧跟在另一个特定字符之后的某个字符出现的索引?
【发布时间】:2017-02-11 07:11:02
【问题描述】:

假设我有一系列推文:

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, '');

}

请帮忙。

【问题讨论】:

标签: javascript


【解决方案1】:

Regex 是你的朋友。

   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);

【讨论】:

    【解决方案2】:
    arr.map(e => e.replace(/(?:^|\W)@(\w+)(?!\w)/g,"") )
    

    一行完成:) ...演示是here

    【讨论】:

      【解决方案3】:

      以@Abdennour 为基础...

      var newArr = arr.map(e => e.replace(/@\w+\s+/,"") );
      

      【讨论】:

        【解决方案4】:

        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++;
        }

        或者你可以使用正则表达式,比如

        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++;
        }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-09-11
          • 2021-11-05
          • 2019-05-28
          • 2017-12-24
          • 2020-09-17
          • 2018-07-18
          • 1970-01-01
          相关资源
          最近更新 更多