Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

regex to get multiple values in javascript

my string is

Cuenta de Ahorros | 1231231231 Bs 102,423.88 Cuenta de Ahorros | 1231233123 Usd 102,423.88 Cuenta de Ahorros | 87316633 Usd 10.233 Cuenta de Ahorros | 49189387113313 Usd 12.301

but using match() i can’t capture all string values

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const strings = [
  "Cuenta de Ahorros | 1231231231 Bs 102,423.88 Cuenta de Ahorros | 1231233123 Usd 102,423.88 Cuenta de Ahorros | 87316633 Usd 10.233 Cuenta de Ahorros | 49189387113313 Usd 12.301"
]; 

let pattern = /(?<=Bs).*?(?=Cuenta)/;
strings.forEach((s) => {
  console.log(s.match(pattern));
});

returns only

[" 102,423.88 ", 40, "Cuenta de Ahor…] 0 : " 102,423.88 "

i need result like

Bs 102,423.88

Usd 102,423.88

Usd 10.233

Usd 12.301

>Solution :

You can use

const strings = [
  "Cuenta de Ahorros | 1231231231 Bs 102,423.88 Cuenta de Ahorros | 1231233123 Usd 102,423.88 Cuenta de Ahorros | 87316633 Usd 10.233 Cuenta de Ahorros | 49189387113313 Usd 12.301"
]; 

let pattern = /\b(?:Bs|Usd)\b.*?(?=\s*Cuenta\b|$)/gi;
strings.forEach((s) => {
  console.log(s.match(pattern));
});

See the regex demo.

Pattern details:

  • \b(?:Bs|Usd)\b – a whole word Bs or Usd
  • .*? – any zero or more chars other than line break chars, as few as possible
  • (?=\s*Cuenta\b|$) – a positive lookahead that requires (immediately to the right of the current location) either zero or more whitespaces and then a whole word Cuenta (\s*Cuenta\b|$), or end of string ($).

I added g flag and used String#match to extract all matches from a string, and i flag makes the search case-insensitive.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading