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-"
?
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 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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With