Home > Net >  javascript regex data until new line
javascript regex data until new line

Time:10-27

I'm trying to remove all sentences if they start with particular character until break line. So far I created something like this but it removes only these particular characters instead of whole line. I'm not good with regex expressions so would be grateful if someone could throw some hint


From: ABC, DEF <[email protected] [mailto:[email protected]]>

Upcoming Events:

Hello hello

Sent: Thursday, February 28, 20117:22 PM


var cleanup = msg.replace(/From.|Sent.|To.|Cc.*\n/g, "");

current output:

ABC, DEF <[email protected] [mailto:[email protected]]>

Upcoming Out of Office:

Hello hello

Thursday, July 29, 2021 7:48 PM


expected output:

Upcoming Out of Office:
Hello hello

CodePudding user response:

You can use

text = text.replace(/^\s*(?:From|Sent|To|Cc)\b.*[\r\n]*\s*/gm)

Or, if you need to also remove empty lines:

text = text.replace(/^(?:\s*(?:From|Sent|To|Cc)\b.*)?[\r\n]*\s*/gm)

See the regex demo #1 and regex demo #2. Details:

  • ^ - start of a line (m flag allows that)
  • \s* - zero or more whitespaces
  • (?:From|Sent|To|Cc) - any of the alternatives
  • \b - a word boundary
  • .* - the rest of the line
  • [\r\n]* - zero or more CR or/and LF chars
  • \s* - zero or more whitespaces.

In the second regex, the \s*(?:From|Sent|To|Cc)\b.* part is made optional so that any libe breaks right after the beginning of a line could get consumed.

JavaScript demo:

const text = "From: ABC, DEF <[email protected] [mailto:[email protected]]>\n\nUpcoming Events:\n\nHello hello\n\nSent: Thursday, February 28, 20117:22 PM";
const rx = /^(?:\s*(?:From|Sent|To|Cc)\b.*)?[\r\n]*\s*/gm;
console.log(text.replace(rx, ""));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related