0

I have a little problem with this url.

I want to get only the numbers on the first drop down and send it like as paramater on API.

dropdown

I create a object with properties:

const dataAPI = { nameStation: '', nameStationNumber: '', dateStation: '', dataHours: '' }

and I want dataAPI.nameStationNumber to save only a number of clicked value.

With this code I get only this string for example:

Chepelarska - 18694 - HPoint-Water level 

dataAPI.nameStation = e.target.innerHTML.replace(/.*\+\s?/, '');

How can I cut only 18694 from река Чепеларска - гр. Асеновград + Chepinska - 10084 - HPoint-Water level

Can I get example how to do that ?

Ben Johnson
  • 753
  • 1
  • 9
  • 18

2 Answers2

1

If you want to extract the first number from a string do this:

const input = 'река Чепеларска - гр. Асеновград + Chepinska - 10084 - HPoint-Water level';
let result = input.replace(/^[^0-9]*([0-9]*).*$/, '$1');
console.log(result);

Explanation of regex:

  • ^ -- anchor at start of string
  • [^0-9]* -- scan over anything not a digit
  • ([0-9]*) -- capture group with all digits
  • .*$ -- anything left over
  • replacement uses the capture group: '$1'
Peter Thoeny
  • 7,379
  • 1
  • 10
  • 20
1

Use regex /[^\d]+/ (replace [^] anything that does not match \d (number))

let string = 'река Чепеларска - гр. Асеновград + Chepinska - 10084 - HPoint-Water level';
let result = string.replace(/[^\d]+/g, '');
console.log(result);
Justinas
  • 41,402
  • 5
  • 66
  • 96
  • It's worth pointing out that this will fail if you have two or more numbers in a string, it will concatenate all digits – Peter Thoeny Feb 13 '23 at 16:46