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

标签 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)

但此选项也会从字符串中返回主题行。

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

最佳答案

使用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"

关于javascript - 正则表达式删除字符串中字符的开头到结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36895952/

相关文章:

javascript - 无法读取未定义的属性 'events'(Google日历API)

javascript - 复选框颜色变为灰色

mysql - 通过掩码(正则表达式)从 MySQL 中获取子字符串

c++ - 查找字符串中的**日期**并将其转换为数字形式

mysql - 有没有办法找到最后一个子字符串?

python - 如何拆分字符串并将其子字符串与子字符串列表匹配? - Python

javascript - 编译时的 Angular 类型保护错误

javascript - ng-click 与 Bootstrap 评级

javascript - 创建一个正则表达式来验证只有一个数字的字符串

python - Python中根据字符分解子字符串