Extract text in Regular Expression in Javascript

56
December 19, 2018, at 07:50 AM

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),

Answer 1

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);

Answer 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.

Answer 3

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)

READ ALSO
Uploading image using mobile image get flipped

Uploading image using mobile image get flipped

I have used 3rd party jquery plugin for cropping imagesIt has been implemented successfully, but when I upload an image from a mobile device after getting cropped it will just rotate 45 degree right or left

54
Storing HTML templates with variables

Storing HTML templates with variables

I'm working on a platform that enables you to use templates provided by the platform and you can change few things in the choosen template (title, text, imageetc)

11
Node.js got limit response size

Node.js got limit response size

I am using the got module in order to make web requestsSometimes, the requested urls serve really large files, but I just need the first 10kB of content, so I want to optimize my network usage

31
How to organize all the different parameters in a separate file

How to organize all the different parameters in a separate file

I am writing a long code that uses many constants, file names, flags, etcI want to organize all of them neatly in a separate text file named parameters

43