1

I have the following string:

'SCAR-20 | Sand Mesh (Battle-Scarred)'

I need to break this into 3 different sections, my output should be 3 variables - example:

var part1 = 'SCAR-20';
var part2 = 'Sand Mesh';
var part3 = 'Battle-Scared';

Though the string will change the structure of the string will always be the same:

'part1 | part2 (part3)'

3 Answers 3

2

I'm pretty bad at regex, but this works;

var str = 'SCAR-20 | Sand Mesh (Battle-Scarred)'
var regex = /(.+) \| (.+) \((.+)\)/
var match = str.match(regex);
var part1 = match[1];
var part2 = match[2];
var part3 = match[3];

DEMO

Sign up to request clarification or add additional context in comments.

Comments

2

You can use this regex to get it:

var re = /^(.*).?\|(.*)\((.*)\)/; 
var str = 'SCAR-20 | Sand Mesh (Battle-Scarred)';
var m;

m = str.match(re,'');
var firstPart = m[1];
var secondPart = m[2].trim();
var thirdPart = m[2];

Comments

0

Alternatively without regex:

var first = 'part1 | part2 (part3)'.split('|');
var second = first[1].split('(');
var part1 = first[0].trim();
var part2 = second[0].trim();
var part3 = second[1].substring(0, second[1].indexOf(')')).trim();
console.log(part1, part2, part3);

Comments

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.