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 ~~~~~~~~~~~~~~开发者_JAVA技巧~
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?
.
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.
精彩评论