Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Digits From a String Before and After Special Character using regex

I have a string like 5|10|20|200|300 and i want to get the First Digit Before | and last digit after | that is 5 and 300.

How would I use regex in javascript to return that numbers??

like image 931
Shaheer Ali Avatar asked Dec 09 '22 07:12

Shaheer Ali


1 Answers

This simplest regex will return the two matches 5 and 300:

^\d+|\d+$

See the matches in the demo.

In JS:

result = yourString.match(/^\d+|\d+$/g);

Explanation

  • ^\d+ matches the beginning of the string and some digits (the 5)
  • OR |
  • \d+$ matches some digits and the end of the string
like image 82
zx81 Avatar answered Jan 11 '23 22:01

zx81