Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - string.replace() text spanning multiple lines?

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?

like image 615
mike Avatar asked May 04 '11 14:05

mike


People also ask

How do you write multiple lines of text in JavaScript?

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.

How do I replace multiples in a string?

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."

How do you write multi line strings in template literals in JavaScript?

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.

What is the delimiter for multi line strings in JavaScript?

Method 1: Multiline-strings are created by using template literals. The strings are delimited using backticks, unlike normal single/double quotes delimiter.


1 Answers

. 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.

like image 127
alex Avatar answered Oct 27 '22 19:10

alex