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]
var test = 'category~[330526|330519]^Size{1}~[m]';
var result = test.split('^').shift();
This should do it:
category~\[\d+\|\d+\]
category
text can be anything. I'm not down voting, just noting.
Commented
Jul 26, 2013 at 12:40
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.
Yet another approach...
var test = 'category~[330526|330519]^Size{1}~[m]';
var result = test.replace(/\^.+/,"");
"category~[330526|330519]^Size{1}~[m]".replace(/(category~[\d+\|\d+]).*/,"$1"), you should get the string, or you can use match as well.
test.replace('^Size{1}~[m]','')
?\d
and+
.