我有一個可能包含Twitter標籤的字符串。我想從字符串中刪除它。我應該怎麼做?我正在嘗試使用RegExp類,但它似乎不工作。我究竟做錯了什麼?使用JavaScript從字符串中刪除hashtags
這是我的代碼:
var regexp = new RegExp('\b#\w\w+');
postText = postText.replace(regexp, '');
我有一個可能包含Twitter標籤的字符串。我想從字符串中刪除它。我應該怎麼做?我正在嘗試使用RegExp類,但它似乎不工作。我究竟做錯了什麼?使用JavaScript從字符串中刪除hashtags
這是我的代碼:
var regexp = new RegExp('\b#\w\w+');
postText = postText.replace(regexp, '');
這裏亞去:
postText = 'this is a #test of #hashtags';
var regexp = new RegExp('#([^\\s]*)','g');
postText = postText.replace(regexp, 'REPLACED');
這裏使用的,而不是在第一次出現停止「G」屬性,這意味着「找到所有的比賽」。
我認爲\ b需要在那裏,否則像'http://twitter.com/#search='這樣的URL會錯誤地被拾取爲散列標籤 – Tom 2011-08-02 17:03:56
這?
<script>
postText = "this is a #bla and a #bla plus#bla"
var regexp = /\#\w\w+\s?/g
postText = postText.replace(regexp, '');
alert(postText)
</script>
這應該是被接受的答案。這些正則表達式中唯一一個正如所描述的那樣工作。豎起大拇指。 :D – azariah 2016-10-31 03:11:12
你可以寫:
// 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
希望它幫助。
請舉個例子輸入 – Topera 2010-08-18 16:38:50