簡體   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