通过正则表达式删除#标签符号js

问题描述 投票:1回答:4

试图在论坛上搜索,但找不到任何与我需要的完全相似的东西。我基本上试图从我收到的结果中删除#符号,这里是正则表达式的虚拟示例。

let postText = 'this is a #test of #hashtags';
var regexp = new RegExp('#([^\\s])', 'g');
postText = postText.replace(regexp, '');

console.log(postText);

它给出了以下结果

this is a est of ashtags

我需要改变什么才能在不删除每个单词的第一个字母的情况下删除主题标签

javascript regex
4个回答
3
投票

你需要一个反向引用$1作为替代品:

let postText = 'this is a #test of #hashtags';
var regexp = /#(\S)/g;
postText = postText.replace(regexp, '$1');
console.log(postText);
// Alternative with a lookahead:
console.log('this is a #test of #hashtags'.replace(/#(?=\S)/g, ''));

注意我建议用正则表达式文字符号替换构造函数表示法以使正则表达式更具可读性,并使用更短的[^\s](任何非空白字符串)更改\S

在这里,/#(\S)/g匹配g的多次出现(由于#修饰符)和它之后的任何非空白字符(在将其捕获到组1中)时,String#replace将用后一个char替换找到的匹配。

或者,为了避免使用反向引用(也称为占位符),您可以使用前瞻,如.replace(/#(?=\S)/g, ''),其中(?=\S)需要立即在当前位置右侧的非空白字符。如果您还需要删除字符串末尾的#,请将(?=\S)替换为(?!\s),如果下一个字符是空格,则会使匹配失败。


1
投票

可能更容易编写自己的函数,可能看起来像这样:(当符号可能重复时覆盖用例)

  function replaceSymbol(symbol, string) {
    if (string.indexOf(symbol) < 0) {
      return string;
    }

    while(string.indexOf(symbol) > -1) {
      string = string.replace(symbol, '');
    }

    return string;
  }



var a = replaceSymbol('#', '##s##u#c###c#e###ss is he#re'); // 'success is here'

1
投票

您可以使用以下内容:

let postText = 'this is a #test of #hashtags';
postText = postText.replace(/#\b/g, '');

它依赖于#hashtag#和跟随它的词之间包含词边界的事实。通过将该词边界与\b匹配,我们确保不匹配单个#

然而,它可能比你想象的要多一点,因为正则表达式中“单词字符”的定义并不明显:它包括数字(因此#123将匹配)和更令人困惑的_字符(所以#___将是匹配)。

我不知道是否有一个权威来源定义这些是否是可接受的标签,所以我会让你判断这是否符合你的需要。


0
投票

你只需要#,parens中的东西匹配其他任何东西后说#

postText = postText.replace('#', '');

这将取代所有#

© www.soinside.com 2019 - 2024. All rights reserved.