简体   繁体   中英

Regex expression to remove start to end of character in string

I have this 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"

And I would like to splice this string from the start until after the "Subject" line so I get the email body content.

I've tried this so far:

string.substring(string.lastIndexOf('Subject'), string.length - 1)

But this option does return the Subject line as well from the string.

Is there a regex library I can use?

Using string.replace you can do:

var body = string.replace(/^[\s\S]*\s+Subject: [^\n]*\n+/, '')

Code:

 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]* matches 0 or more of any characters including newline. It is followed by Subject: line which is also removed.

Output:

"Hi Mark, 
<br />
I'm sending this email as a way to test the email! 
<br />
Cheers, 
<br />
Jeremy"

Someone will give you the non-regex solution, but here is one with regex

[\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>"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM