繁体   English   中英

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

[英]Strip hashtags from string using JavaScript

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

这是我的代码:

var regexp = new RegExp('\b#\w\w+');
postText = postText.replace(regexp, '');

给你:

postText = 'this is a #test of #hashtags';
var regexp = /#\S+/g;
postText = postText.replace(regexp, 'REPLACED');

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

你可以写:

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

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

g 启用“全局”匹配。 使用 replace() 方法时,指定此修饰符以替换所有匹配项,而不仅仅是第一个匹配项。

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

希望能帮助到你。

这个?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM