簡體   English   中英

JavaScript正則表達式,搜索主題標簽

[英]JavaScript regex, searching for hashtags

如何在一些文本中搜索任何和所有主題標簽(字母數字和下划線和連字符)並將其包裝在span標簽中,例如搜索

some_string = "this is some text with 3 hashtags #Tag1 and #tag-2 and #tag_3 in it"

並將其轉換為:

"this is some text with 3 hashtags <span>#Tag1</span> and <span>#tag-2</span> and <span>#tag_3</span> in it"

到目前為止我有這個:

    some_string = some_string.replace(/\(#([a-z0-9\-\_]*)/i,"<span>$1</span>");

但有一個錯誤是它不包括應該包裝的#。 它似乎輸出:

"this is some text with 3 hashtags <span>Tag1</span> and #tag-2 and #tag_3 in it "

此外,它只檢測它遇到的第一個#Tag1標簽(例如,此示例中的#Tag1 ),它應該檢測所有。

此外,我需要#標簽后至少有1個字符。 所以#本身不應該匹配。

謝謝

試試這個替換電話:

編輯:如果你想跳過http://site.com/#tag類型的字符串然后使用:

var repl = some_string.replace(/(^|\W)(#[a-z\d][\w-]*)/ig, '$1<span>$2</span>');

這是您想要的正則表達式:

/(#[a-z0-9][a-z0-9\-_]*)/ig

i使它不區分大小寫,你已經擁有它。 但是g使它看起來整個字符串(“g”代表“全局”)。 沒有g ,匹配在第一場比賽時停止。

這還包括修復刪除不正確的括號和一些不需要的反斜杠。

適用於多行和非拉丁符號的解決方案:

var getHashTags = function(string) {
   var hashTags, i, len, word, words;
   words = string.split(/[\s\r\n]+/);
   hashTags = [];
   for (i = 0, len = words.length; i < len; i++) {
     word = words[i];
     if (word.indexOf('#') === 0) {
       hashTags.push(word);
     }
   }
   return hashTags;
};

或者在CoffeeScript中:

getHashTags = (string) ->
  words = string.split /[\s\r\n]+/
  hashTags = []
  hashTags.push word for word in words when word.indexOf('#') is 0
  hashTags

如果您不想匹配http://site/#hashs ,請使用此代碼*:

string.replace(/(^|\s)#[a-zA-Z0-9][\w-]*\b/g, "$1<span>$2</span>");

它將匹配:

  • #word
  • #word_1#word-1
  • #word中的#word? #word"#word.#word,

它不匹配

  • "#word nor ,#word nor .#word
  • /#word
  • #_word也不是#-word
  • wor#d

您想要和不想匹配的內容可能會因情況而異。

regex101自己試試吧。


* @anubhava發布的當前接受的答案聲稱跳過url hash,但沒有做到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM