user2025749
user2025749

Reputation: 281

Match string using regex

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]

Upvotes: 1

Views: 81

Answers (7)

gvmani
gvmani

Reputation: 1600

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

Upvotes: 0

ic3b3rg
ic3b3rg

Reputation: 14937

Yet another approach...

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

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

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67928

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.

Upvotes: 0

Dave Sexton
Dave Sexton

Reputation: 11188

This should do it:

category~\[\d+\|\d+\]

Upvotes: 1

Alex K.
Alex K.

Reputation: 175976

You could;

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

Upvotes: 1

adeneo
adeneo

Reputation: 318352

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

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

FIDDLE

Upvotes: 3

hsz
hsz

Reputation: 152304

Just try with:

test.split('^')[0];

Upvotes: 6

Related Questions