user2133455
user2133455

Reputation: 7

Split a string for values outside parenthesis

I have a string - 'A(10), B(20), C(30), D(40), E(10), F(0),'

I want to split it so that I get all the values outside the parenthesis split by comma.

OUTPUT - A B C D E F

I am trying to do this in JavaScript. Any ideas?

Upvotes: 0

Views: 1814

Answers (4)

David Thomas
David Thomas

Reputation: 253318

Why not simply:

var str = 'A(10), B(20), C(30), D(40), E(10), F(0),';
console.log(str.match(/([A-Z])(?=\()/g)); // ["A", "B", "C", "D", "E", "F"]

JS Fiddle demo.

Updated, for the requirement of 'integers or characters':

var str = 'A3(10), aB(20), 34(30), D(40), E(10), F(0),';
console.log(str.match(/([A-Z0-9]+)(?=\()/g)); // ["A3", "B", "34", "D", "E", "F"] 

JS Fiddle demo.

If you'd prefer a simple string, rather than an array:

var str = 'A3(10), aB(20), 34(30), D(40), E(10), F(0),';
console.log(str.match(/([A-Z0-9]+)(?=\()/g)).join(' '); // A3 B 34 D E F 

JS Fiddle demo.

References:

Upvotes: 1

Drew
Drew

Reputation: 4373

var str = 'A(10), B(20), C(30), D(40), E(10), F(0),';
var sections = str.split(',');
var myRegexp = /^(?:\s+)?([^\(]+)/;
var results = new Array();
for (var i = 0; i < sections.length; i++) {
    if(sections[i]){
        var match = myRegexp.exec(sections[i]);
        if(match[1]){
             results[results.length] = match[1];
        }
    }
}
console.log(results); // outputs: ["A", "B", "C", "D", "E", "F"]
alert(results.join(' - ')); // alerts: A - B - C - D - E - F

Upvotes: 0

Sean Bright
Sean Bright

Reputation: 120644

Assuming that the string you've supplied is 100% representative of what you are trying to extract data from, you can just do this:

var str = 'A(10), B(20), C(30), D(40), E(10), F(0),';
str = str.replace(/\(\d+\)/g, '');

Here is a jsFiddle showing that it works.

Upvotes: 0

Bergi
Bergi

Reputation: 664434

split it so that I get all the values outside the parenthesis split by comma

Remove the parenthesis pairs and then split:

'A(10), B(20), C(30), D(40), E(10), F(0),'.replace(/\(\d+\)/g,"").split(/,\s*/);
// ["A", "B", "C", "D", "E", "F", ""]

To get the output you wanted you might better use a match with a lookahead ("word characters before an opening bracket, some none-bracket characters, a closing bracket and a comma"):

'A(10), B(20), C(30), D(40), E(10), F(0),'.match(/\w+(?=\([^)]*\),)/g);
// ["A", "B", "C", "D", "E", "F"]

or just do a .match(/[A-Z]+/g) for simplicity?

Upvotes: 0

Related Questions