我有这个字符串:
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)
但是这个选项确实从字符串返回主题行。
我可以使用正则表达式库吗?
答案 0 :(得分:3)
使用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"
答案 1 :(得分:0)
有人会给你非正则表达式解决方案,但这里有一个正则表达式
[\s\S]*Subject\s*:.*([\s\S]+) <-- your result in first capturing group
<强> Regex Demo 强>
JS Demo
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>");