使用JavaScript从字符串中删除主题标签

问题描述 投票:8回答:3

我有一个可能包含Twitter主题标签的字符串。我想把它从字符串中删除。我该怎么做?我正在尝试使用RegExp类但它似乎不起作用。我究竟做错了什么?

这是我的代码:

var regexp = new RegExp('\b#\w\w+');
postText = postText.replace(regexp, '');
javascript twitter
3个回答
13
投票

你走了:

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

这使用'g'属性,这意味着'找到所有匹配',而不是在第一次出现时停止。


6
投票

你可以写:

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

我没有看到第一个\w的共鸣。 +标志用于一个或多个出现。 (或者你只对两个字符的主题标签感兴趣吗?)

g enables "global" matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one.

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

希望能帮助到你。


2
投票

这个?

postText = "this is a #bla and a #bla plus#bla"
var regexp = /\#\w\w+\s?/g
postText = postText.replace(regexp, '');
console.log(postText)
© www.soinside.com 2019 - 2024. All rights reserved.