1

I'm trying to replace everything in between [lorem] and [/lorem]. For example:

[lorem]Here goes some text[/lorem]

will turn into

These is inside a lorem block

I've manged to make it work with [[Here goes some text]], using

var block = $('body').html().replace(/\[[^\]]+\]]/ig, "This is inside a lorem block");
$('body').html(block);

but I can't, for the life of me, make it work using the former, either because I'm doing something wrong or I don't actually understand how that works. Also, what does ^ in the replace function do? I'm guessing it means something like "anything in between" but of course I could be wrong. Where can I read about those?

1 Answers1

2

Try using the RegExp /\[lorem\].*?\[\/lorem\]/ig:

var block = $('body').html().replace(/\[lorem\].*?\[\/lorem\]/ig, "This is inside a lorem block");
$('body').html(block);


EDIT:

To allow for newline characters use the following: (credit to @PatrickAllen)

var block = $('body').html().replace(/\[lorem\][\s\S]*?\[\/lorem\]/ig, "This is inside a lorem block");
$('body').html(block);
Lugia101101
  • 685
  • 1
  • 7
  • 21
  • Ah that's great, it works! Quick question, what if there's a line break inside the `[lorem][/lorem]`? This works great when it's in a single line but for some reason it stops when I put breaks. – user3047675 Apr 20 '14 at 22:58
  • Would adding the `m` flag help? – Lugia101101 Apr 20 '14 at 23:00
  • 1
    use `[\s\S]` instead of a `.` There is no m flag in JS. So use this: `/\[lorem\][\s\S]*?\[\/lorem\]/ig` – Patrick Allen Apr 20 '14 at 23:05
  • Ah yes, Just found out about [\s\S] from http://stackoverflow.com/questions/1068280 right before this and it works now. The `m` flag doesn't work as @PatrickAllen said. Thanks, you guys! – user3047675 Apr 20 '14 at 23:10
  • @PatrickAllen There is an `m` flag, just thinking about a different functionality. – Lugia101101 Apr 20 '14 at 23:10