12

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-" ?

asked Oct 17, 2010 at 21:18
2
  • 2
    Following what rule? Extract all numbers? What is the desired outcome, an array? Commented Oct 17, 2010 at 21:20
  • no, just the number/string after those parameters. output should be a string Commented Oct 17, 2010 at 21:38

3 Answers 3

38

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)

Aniket Kulkarni
13k10 gold badges70 silver badges94 bronze badges
answered Oct 18, 2010 at 1:06
Sign up to request clarification or add additional context in comments.

Comments

17

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.

answered Oct 17, 2010 at 21:21

Comments

6

You can use regexp as explained by w3schools. Hint:

str = "blabla blabla-5 amount-10 blabla direction-left"
alert(str.match(/amount-([0-9]+)/));

Otherwize you can simply want all numbers so use the pattern [0-9]+ only. str.match would return an array.

answered Oct 17, 2010 at 21:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.