1

I am trying to match something like [allchar] with a regular expression and be able to pull it out and replace it with other content

Here is what I am trying

var text = "[abc123.;.] this is more content";
var replacewith = "[contentreplacedwith]";

reg = new RegExp("/\[{1}.*?\]{1}/g");
if(reg.test(text))
{

    txt = $('#message').val().replace(text,'[' + replacewith + ']');
    console.log(txt);
}

The result should be

    [contentreplacedwith] this is more content
Tom
  • 761
  • 3
  • 15
  • 33
  • off the top of my head. I don't know js regex but try `/\[[^\]]*\]/g`. Don't know where to put the group id. So you'll have to figure that out. – Reactgular Aug 20 '13 at 22:03
  • 2
    What is `new RegExp("/\[{1}.*?\]{1}/g");`? That's not how you create regular expression objects. Regex **literals** are denoted by `/ /flags`. Regex objects can be created by passing a pattern with `new RegExp("pattern", "flags")`, not the string version of a literal. Read about them both here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions – Ian Aug 20 '13 at 22:04
  • 1) It's helpful if you can include the actual result of your current code along with your expected result. 2) FYI, you don't need the `{1}`s - a character in a regex is assumed to be occurring once. – Michelle Aug 20 '13 at 22:05
  • You want to capture all that are *not* `]` before the `]` otherwise it'll over capture. That's how i capture quoted text. – Reactgular Aug 20 '13 at 22:05

1 Answers1

2
reg = new RegExp("\\[.*?\\]", "g");
x = "[abc123.;.] this is more content";
console.log(x.replace(reg, "[contentreplacedwith]"));

If you use RegExp constructor the there's no need to pass / delimiters and the options like g for global are a second argument.

6502
  • 112,025
  • 15
  • 165
  • 265
  • +1, but wouldn't `"\\[[^\]]*?\\]"` work better? that's my experience. – Reactgular Aug 20 '13 at 22:06
  • 1
    @MathewFoscarini: backslashes must be doubled inside double quotes, and the question mark after the asterisk is what makes the match non-greedy (grab as few char as possible that make the whole regexp succeed). In this case `.*?` is equivalent to `[^]]*` (and the question mark is not needed). – 6502 Aug 20 '13 at 22:09
  • 2
    OMG. I think that's the first time someone has explained what greety means in a way that was easy to understand. Thanks. – Reactgular Aug 20 '13 at 22:11