![](/img/trans.png)
[英]Regex Expression to remove certain characters from string expect at the start and end
[英]Regex expression to remove start to end of character in string
我有這個字符串:
var string = "From: Jeremy<br />
Sent: 22 Apr 2016 12:08:03</br />
To: Mark<br />
Subject: Another test email<br /><br />
Hi Mark,
<br />
I'm sending this email as a way to test the email!
<br />
Cheers,
<br />
Jeremy"
並且我想從頭開始拼接該字符串,直到“主題”行之后,以便獲得電子郵件正文內容。
到目前為止,我已經嘗試過了:
string.substring(string.lastIndexOf('Subject'), string.length - 1)
但是此選項的確從字符串中返回主題行。
我可以使用正則表達式庫嗎?
使用string.replace
可以執行以下操作:
var body = string.replace(/^[\s\S]*\s+Subject: [^\n]*\n+/, '')
碼:
var string = `From: Jeremy<br /> Sent: 22 Apr 2016 12:08:03</br /> To: Mark<br /> Subject: Another test email<br /><br /> Hi Mark, <br /> I'm sending this email as a way to test the email! <br /> Cheers, <br /> Jeremy` var body = string.replace(/^[\\s\\S]*\\s+Subject: [^\\n]*\\n+/, '') document.writeln("<pre>" + body + "</pre>")
[\\s\\S]*
匹配0個或多個任何字符,包括換行符。 緊隨其后的是Subject:
行。
輸出:
"Hi Mark,
<br />
I'm sending this email as a way to test the email!
<br />
Cheers,
<br />
Jeremy"
有人會給您非正則表達式的解決方案,但這是一個帶有正則表達式的解決方案
[\s\S]*Subject\s*:.*([\s\S]+) <-- your result in first capturing group
JS演示
var re = /[\\s\\S]*Subject\\s*:.*([\\s\\S]+)/gm; var str = `From: Jeremy<br /> Sent: 22 Apr 2016 12:08:03</br /> To: Mark<br /> Subject: Another test email<br /><br /> Hi Mark, <br /> I'm sending this email as a way to test the email! <br /> Cheers, <br /> Jeremy` var m = re.exec(str); document.writeln("<pre>" + m[1] + "</pre>");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.