簡體   English   中英

javascript從字符串中提取主題標簽

[英]javascript extract hashtags from strings

我有一個從后端收到的字符串,我需要提取主題標簽。 標簽以以下兩種形式之一書寫

type 1. #World is a #good #place to #live.
type 2. #World#place#live.

我設法通過以下方式從第一種類型中提取: str.replace(/#(\\S*)/g我如何才能將第二種格式更改為以空格分隔的標記以及第一種格式?

基本上我想從格式2轉換為

 #World#place#live.

 #World #place #live.

您可以將String.match與正則表達式#\\w+

 var str = ` type 1. #World is a #good #place to #live. type 2. #World#place#live.` var matches = str.match(/#\\w+/g) console.log(matches) 

\\w+多次匹配任何單詞字符[a-zA-Z0-9_],因此您可能需要對其進行調整。

將比賽安排在一個數組中后,您可以將其重新排列為自己喜歡的。

模式#(\\S*)將與#匹配,后跟0+乘以捕獲組中的非空白字符。 那也將匹配一個#。 字符串#World#place#live. 不包含空格字符,因此整個字符串將被匹配。

您可以使用否定的字符類來匹配它們。 匹配#,然后是與#或空格字符不匹配的否定字符類。

#[^#\s]+

正則表達式演示

 const strings = [ "#World is a #good #place to #live.", "#World#place#live." ]; let pattern = /#[^#\\s]+/g; strings.forEach(s => { console.log(s.match(pattern)); }); 

使用regex /#([\\w]+\\b)/gm並按空格連接怎么樣 像下面#hastags從字符串中提取#hastags 或者您可以使用@Wiktor注釋的str.replace str.replace(/\\b#[^\\s#]+/g, " $&")

 function findHashTags(str) { var regex = /#([\\w]+\\b)/gm; var matches = []; var match; while ((match = regex.exec(str))) { matches.push(match[0]); } return matches; } let str1 = "#World is a #good #place to #live." let str2 = "#World#place#live"; let res1 = findHashTags(str1); let res2 = findHashTags(str2); console.log(res1.join(' ')); console.log(res2.join(' ')); 

暫無
暫無

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

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