1

I have the following variable:

var test = category~[330526|330519]^Size{1}~[m]

How do I match just to get category~[330526|330519] using regex.

This value can also change so it could be category~[3303226|333219]

4
  • 3
    Is that value supposed to be a string? Commented Jul 26, 2013 at 12:34
  • Why not just test.replace('^Size{1}~[m]','')?
    – putvande
    Commented Jul 26, 2013 at 12:35
  • In the spirit of teaching a man to fish... Have a look at regular-expressions.info/reference.html, you're probably looking for \d and +.
    – ohaal
    Commented Jul 26, 2013 at 12:36
  • That ain't JavaScript.
    – James M
    Commented Jul 26, 2013 at 12:36

7 Answers 7

6

Just try with:

test.split('^')[0];
3
var test = 'category~[330526|330519]^Size{1}~[m]';

var result = test.split('^').shift();

FIDDLE

1

You could;

 result = test.substr(0, test.indexOf("]") +1);
1

This should do it:

category~\[\d+\|\d+\]
2
  • I'm pretty sure the category text can be anything. I'm not down voting, just noting. Commented Jul 26, 2013 at 12:40
  • Your welcome - feel free to accept it as the best answer if it is the one you are going with. Commented Jul 29, 2013 at 9:17
0

If you insist on using a Regex, this one doesn't care about what the category is (.*~\[\d+\|\d+\]). Here is a Rubular to prove it. But I have to say, the answer by @hsz is really the most insightful. The split is probably the right tool for the job.

0

Yet another approach...

var test = 'category~[330526|330519]^Size{1}~[m]';

var result = test.replace(/\^.+/,"");
0

"category~[330526|330519]^Size{1}~[m]".replace(/(category~[\d+\|\d+]).*/,"$1"), you should get the string, or you can use match as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.