正则表达式删除字符串中字符的开头到结尾

时间:2016-04-27 16:45:22

标签: javascript regex substring splice

我有这个字符串:

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)

但是这个选项确实从字符串返回主题行。

我可以使用正则表达式库吗?

2 个答案:

答案 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>");

相关问题