最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited May 4, 2011 at 14:17 alex 490k204 gold badges889 silver badges991 bronze badges asked May 4, 2011 at 14:09 mikemike 3021 gold badge3 silver badges13 bronze badges 2
  • had you consider replacing the text using regular expressions? – marcelo-ferraz Commented May 4, 2011 at 14:11
  • I'm pretty horrible with regx's, definitely something I need to work on. Thanks for the answer Alex! – mike Commented May 4, 2011 at 14:14
Add a comment  | 

1 Answer 1

Reset to default 21

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

发布评论

评论列表(0)

  1. 暂无评论