2017-08-25 63 views
2

我從字符串中提取主題標籤是這樣的:提取從字符串中的所有主題標籤#無

const mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa'; 
const hashtags = mystring.match(/#\w+/g) || []; 
console.log(hashtags); 

輸出:

['#arebaba', '#ole', '#cool', '#aaa'] 

我正則表達式應該如何讓比賽是:

['arebaba', 'ole', 'cool', 'aaa'] 

我不想使用地圖功能!

+0

的可能的複製[怎麼辦我在JavaScript中檢索正則表達式的所有匹配?](https://stackoverflow.com/問題/ 6323417 /如何檢索所有匹配的正則表達式在JavaScript) – choasia

+2

閱讀正則表達式捕獲組。 http://www.regular-expressions.info/brackets.html –

回答

4

const mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa'; 
 
var regexp = /#(\w+)/g; 
 
var match = regexp.exec(mystring); 
 
while (match != null){ 
 
    console.log(match[1]) 
 
    match = regexp.exec(mystring) 
 
}

編輯代碼可以縮短。然而,這不是你的正則表達式能夠解決你的問題,而是選擇正確的方法。

var mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa', 
 
    match; 
 
var regexp = /#(\w+)/g;  
 
while (match = regexp.exec(mystring)) 
 
    console.log(match[1]);

+0

這樣做的竅門,但我不知道如何適應我的用例。我的2行代碼在你的例子中變成了7。我只需要改變我的正則表達式,但不知道應該是什麼。 –

+0

任何機會使用原型? –

2

你已經匹配的多子,你知道前面有#,所以只是將其刪除:

const mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa'; 
 
const hashtags = mystring.match(/#\w+/g).map(x => x.substr(1)) || []; 
 
console.log(hashtags);

+0

在問題中指定:我不想使用地圖功能。 –

+0

@mlambrichs是的,但這不是爲了OP,而是爲了那些想要使用它的人。這個答案是一個社區維基答案。不要使用'.map'的要求是「人造」,聽起來像是一些學校作業,而不是現實生活。 –

+0

我目前正在處理地圖,但是我想跳過這一步並提取已經沒有#的de標籤。 –

相關問題