I have a link that comes in as a string, for example:
let data = [
'/api/customer’,
'/api/customer/123’,
'/api/customer/123/details’
];
I need to extract the numeric ID if there is one. The only way I found is trough _.isNaN():
const myStrArray = type.split('/');
const numericsArray = _.filter(myStrArray, urlPart => !_.isNaN(parseInt(urlPart, 10)));
const id = numericsArray[0]; // undefined/123
Is there a better way to do this?
You can iterate the array with Array.flatMap()
(or lodash _.flatMap()
), and use String.match()
with a RegExp to get a sequence of numbers.
Note: this RegExp assumes that these are the only numbers in the string. You might want to fine tune it, if there's a possibility for other numbers.
let data = [ '/api/customer', '/api/customer/123', '/api/customer/123/details' ]; const result = data.flatMap(str => str.match(/\\d+/)); console.log(result);
User regex and Array#map and Array#flat like so. You need to use ||[]
in case a number was not found.
const data = [ '/api/custome', '/api/customer/123', '/api/customer/123/details' ]; const res = data.map(a=>a.match(/\\d+/)||[]).flat(); console.log(res);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.