Michael Ozoemena Michael Ozoemena - 2 months ago 5
Javascript Question

How to get remove some string out of a larger string in JavaScript, when I don't know their positions

I have this text:

Blah Blah Blah SPECIAL TEXT: PART OF IT
blah bah SPECIAL TEXT: STILL PART OF IT
blah blah blah blah


How do I use JavaScript to get this result:

Blah Blah Blah
blah bah
blah blah blah blah


How do I remove the text in capital letters.

Note that the part after the ":" and before the line break is not meant to be in capital, but it's part of the text that has to go, so I can't just say remove all text in capital.

Also note that I do not know exactly where the text to be removed will start and end, what I do know is that it starts when there is an occurrence of several consecutive capital letters typed side by side and ends when there is a line break.

I've tried getting the index of the first few capital letters by just using
search("SPECIAL")
, and getting the end by using
search("\n")
. The issue with this is getting the line break after the "SPECIAL TEXT" and no other.

So finally, if I do get the positions, both starting and ending, I guess I could just get whatever string is in between the two indexes, and replace them with an empty string and iterate the process.

Any help will be appreciated.

Answer

How about this regular expression?

("Blah Blah Blah SPECIAL TEXT: PART OF IT\n" +
"blah bah SPECIAL TEXT: STILL PART OF IT\n" +
"blah blah blah blah").replace(/SPECIAL\sTEXT:.+$/mg,'')

This basically means replace any string fragments starting with SPECIAL TEXT: followed by some characters (.+) and ending with end of line ($). Examine all lines individually instead of whole string at once (m) and don't stop after the first one replacement (g)

Comments