[英]JavaScript - Regex split string to array allowing for apostrophes
我有一些 Express 中間件,它處理一個字符串——用戶通過文本字段輸入的句子——並對其進行一些分析。 為此,我需要將單詞和標點符號分成一個數組。
一個示例字符串是:
"It's familiar. Not much has really changed, which is surprising, but
it's nice to come back to where I was as a kid."
作為過程的一部分,我用<br />
替換新行並將字符串拆分為一個數組
res.locals.storyArray =
res.locals.story.storyText.replace(/(?:\r\n|\r|\n)/g, ' <br/>' ).split(" ");
這在一定程度上是有效的,但是當一個句子包含一個撇號時,例如"It's familiar.
事情變得不同步,我得到一個數組(請注意,我沒有在這里展示關於單詞如何映射到它的細節)語法類型):
[ [ '"', 'quote' ],
['It', 'Personal pronoun' ], <--these items are the issue
[ '\'', 'quote' ], < --------these items are the issue
[ 's', 'Personal pronoun'], <------these items are the issue
[ 'familiar', 'Adjective' ],
[ '.', 'Sent-final punct' ],
[ 'Not', 'Adverb' ],
[ 'much', 'Adjective' ],
[ 'has', 'Verb, present' ],
[ 'really', 'Adverb' ],
[ 'changed', 'verb, past part' ],
[ ',', 'Comma' ],
[ 'which', 'Wh-determiner' ],
[ 'is', 'Verb, present' ]]
我實際上很驚訝逗號和句號似乎被正確分割,看到我只在空白處分割,但我試圖讓我的數組是:
[ [ '"', 'quote' ],
[ 'It's, 'Personal pronoun' ],
[ 'familiar', 'Adjective' ],
[ '.', 'Sent-final punct' ],
.....
]
您可以使用String.raw
來確保字符串與包含的標點符號保持正確一致。
我唯一的問題是保留“。” 標點符號。 為此,我在拆分.replace(/\\./g, " .")
之前添加了一個新的替換函數 - 這對所有逗號也是如此。
let strArray = myStr.replace(/\./g, " .")
.replace(/\,/g, " ,")
.replace(/\"/g, String.raw` " `)
.split(/\s/g)
.filter(_=>_);
let myStr = String.raw `"It's familiar. Not much has really changed, which is surprising, but it's nice to come back to where I was as a kid."`; let strArray = myStr.replace(/\\./g, " .") .replace(/\\,/g, " ,") .replace(/\\"/g, String.raw` " `) .split(/\\s/g) .filter(_=>_); let HTML = myStr.replace(/(?:\\r\\n|\\r|\\n)/g, " <br/>"); console.log(myStr); console.log(strArray);
編輯:也添加了逗號分隔的replace
。
我不知道你所期望的對做<br/>
-它似乎傻插入他們試圖把你的字符串到一個數組。 在代碼中,我已經分離了這個過程。 您現在有一個帶有<br/>
標簽的字符串和另一個包含數組的變量。
如果您有任何補充信息,如果這不能解決您的問題,我很樂意提供幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.