Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript / Jquery - Get number from string

the string looks like this

"blabla blabla-5 amount-10 blabla direction-left"

How can I get the number just after "amount-", and the text just after "direction-" ?

like image 968
Alex Avatar asked Oct 17 '10 21:10

Alex


People also ask

How to get number out of string JavaScript?

The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).

How do I search for a specific word in a string in jquery?

How to find if a word or a substring is present in the given string. In this case, we will use the includes() method which determines whether a string contains the specified word or a substring. If the word or substring is present in the given string, the includes() method returns true; otherwise, it returns false.


2 Answers

This will get all the numbers separated by coma:

var str = "10 is smaller than 11 but greater then 9";
var pattern = /[0-9]+/g;
var matches = str.match(pattern);

After execution, the string matches will have values "10,11,9"

If You are just looking for thew first occurrence, the pattern will be /[0-9]+/ - which will return 10

(There is no need for JQuery)

like image 58
Ed.C Avatar answered Oct 26 '22 17:10

Ed.C


This uses regular expressions and the exec method:

var s = "blabla blabla-5 amount-10 blabla direction-left";
var amount = parseInt(/amount-(\d+)/.exec(s)[1], 10);
var direction = /direction-([^\s]+)/.exec(s)[1];

The code will cause an error if the amount or direction is missing; if this is possible, check if the result of exec is non-null before indexing into the array that should be returned.

like image 28
PleaseStand Avatar answered Oct 26 '22 18:10

PleaseStand