代码之家  ›  专栏  ›  技术社区  ›  Vitor Py

使用JavaScript从字符串中去除hashtag

  •  7
  • Vitor Py  · 技术社区  · 15 年前

    我有一个可能包含Twitter标签的字符串。我想把它从绳子上取下来。我该怎么做?我试图使用RegExp类,但它似乎不起作用。我做错什么了?

    var regexp = new RegExp('\b#\w\w+');
    postText = postText.replace(regexp, '');
    
    3 回复  |  直到 15 年前
        1
  •  14
  •   Ian McIntyre Silber    15 年前

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

    它使用“g”属性,即“查找所有匹配项”,而不是在第一次出现时停止。

        2
  •  5
  •   MartyIX    15 年前

    你可以写:

    // g denotes that ALL hashags will be replaced in postText    
    postText = postText.replace(/\b\#\w+/g, ''); 
    

    我第一次看不出原因 \w + 符号用于一个或多个事件(或者你只对两个字符的标签感兴趣?)

    资料来源: http://www.regular-expressions.info/javascript.html

    希望有帮助。

        3
  •  3
  •   mplungjan    7 年前

    这个?

    postText = "this is a #bla and a #bla plus#bla"
    var regexp = /\#\w\w+\s?/g
    postText = postText.replace(regexp, '');
    console.log(postText)