Let's say I have text (not html), that I'm pulling from a textarea. It looks like:
ALTER LOGIN [user1] DISABLE
GO
~~~~~~~~~~~~~ important stuff to keep ~~~~~~~~~~~~~~~
~~~~~~~~~~~~~ important stuff to keep ~~~~~~~~~~~~~~~
~~~~~~~~~~~~~ important stuff to keep ~~~~~~~~~~~~~~~
ALTER LOGIN [user2] DISABLE
GO
~~~~~~~~~~~~~ important stuff to keep ~~~~~~~~~~~~~~~
~~~~~~~~~~~~~ important stuff to keep ~~~~~~~~~~~~~~~
~~~~~~~~~~~~~ important stuff to keep ~~~~~~~~~~~~~~~
I'm trying to delete from ALTER to GO for each user. With replace(), I can replace from ALTER to DISABLE, but I can't quite figure out how to match all the way to GO (which is on the next line), so that it removes the whole chunk. Thoughts?
There are three ways to create strings that span multiple lines: By using template literals. By using the + operator – the JavaScript concatenation operator. By using the \ operator – the JavaScript backslash operator and escape character.
replace(/cat/gi, "dog"); // now str = "I have a dog, a dog, and a goat." str = str. replace(/dog/gi, "goat"); // now str = "I have a goat, a goat, and a goat." str = str. replace(/goat/gi, "cat"); // now str = "I have a cat, a cat, and a cat."
There are three ways to create a multiline string in JavaScript. We can use the concatenation operator, a new line character (\n), and template literals. Template literals were introduced in ES6. They also let you add the contents of a variable into a string.
Method 1: Multiline-strings are created by using template literals. The strings are delimited using backticks, unlike normal single/double quotes delimiter.
.
in a regex matches every character except \n
. In some regex flavours, you can add the s
flag to make it match them, but not in Javascript.
Instead, you can use the [\s\S]
character class, which matches all whitespace and all non whitespace, which is everything. The ?
after *
means it won't be greedy, otherwise it will match between the first ALTER
and the last GO
.
str = str.replace(/ALTER[\s\S]*?GO/g, '');
jsFiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With