1

In Javascript, I want to extract array from a string. The string is

var str = "abc (24 314 83 383)(-256)sa 0 (24 314) 1"

I want priority to be the text in parentheses then other text separated by white space. So for the above example, the result should to be:

result[0] = "abc"
result[1] = "24 314 83 383"
result[2] = "-256"
result[3] = "sa"
result[4] = "0"
result[5] = "24 314"
result[6] = "1"

I tried

var pattern = /(.*?)[\s|\)]/g;
result = str.match(pattern);

but the result was: abc ,(24 ,314 ,83 ,383),(-256),sa ,0 ,(24 ,314),

3
  • The posted question does not appear to include any attempt at all to solve the problem. StackOverflow expects you to try to solve your own problem first, as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific roadblock you're running into a minimal reproducible example. For more information, please see How to Ask and take the tour. Commented Dec 19, 2018 at 1:23
  • Where has the 0 in the original string gone? Commented Dec 19, 2018 at 1:26
  • You can use: /(?!()[\w -]+(?=))|[\w-]+/g That will do it in one shot. Commented Dec 19, 2018 at 2:59

3 Answers 3

2

Here's a solution using a regex object and exec, which is safer than filtering out parenthesis with something like str.match(/\w+|\((.*?)\)/g).map(e => e.replace(/^\(|\)$/g, "")):

var str = "abc (24 314 83 383)(-256)sa 0 (24 314) 1";
var reg = /\w+|\((.*?)\)/g;
var match;
var res = [];

while (match = reg.exec(str)) {
  res.push(match[1] || match[0]);
}

console.log(res);

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

Comments

2

You can try this:

let str = "abc (24 314 83 383)(-256)sa 0 (24 314) 1";
let replaced = str.replace(/(\s*\(|\))/g, '<REP>');
let arrFromStr = replaced.split('<REP>').filter(w => w.length != 0);

Variable "replaced" replaces all 1) 0 or more spaces + "(", and 2) all ")" symbols to "" string. arrFromStr creates an array from string and split it with "". Then we check is the element of array empty, or not.

2 Comments

Some explanation of what this is doing (explaining why it works) would be helpful.
Is this a good explanation?) Maybe I said something wrong. My English is not perfect yet.
1

try this:

var str = "abc (24 314 83 383)(-256)sa 0 (24 314) 1"
var pattern = /\((.*?)\)|\s?(\S+)\s?/g;
var result = str.match(pattern).map(v => v.trim().replace(/^\(|\)$/g, ''));
console.log(result)

2 Comments

Thanks, it had a trailing space in the array items. I accepted another solution since it was do the work perfectly
@MostafaFouda, you can add .trim(), see the updated answer.

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.