1

I want to extract numbers from a string in javascript like following :

if the string = 'make1to6' i would like to extract the numeric character before and after the 'to' substring in the entire string. i.e. 1 and 6 are to be extracted

The length of the string is not fixed and can be a max of 10 characters in length.The number can be of max two digits on either side of 'to' in the string.

Possible string values :

  • sure1to3
  • ic3to9ltd
  • anna1to6
  • joy1to4val
  • make6to12
  • ext12to36

thinking of something like :

function beforeTo(string) {
    return numeric_value_before_'to'_in_the_string;
}

function afterTo(string) {
    eturn numeric_value_after_'to'_in_the_string;
}

i will be using these returned values for some calculations.

2 Answers 2

6

Here's an example function that will return an array representing the two numbers, or null if there wasn't a match:

function extractNumbers(str) {
    var m = /(\d+)to(\d+)/.exec(str);
    return m ? [+m[1], +m[2]] : null;
}

You can adapt that regular expression to suit your needs, say by making it case-insensitive: /(\d+)to(\d+)/i.exec(str).

Sign up to request clarification or add additional context in comments.

1 Comment

@Sandy505: Well, you recognize the regular expression, right? /(\d+)to(\d+)/. We'll start with that. \d means "any digit, from 0 to 9." \d+ means "at least one digit." to just matches the word "to." .exec executes the expression on the string, and turns it into an array of matches. So m[1] is the first group of digits, and m[2] is the second group of digits... we return those in an array if it matched. That's it. You can now access the first number as myArray[0] and the second as myArray[1].
1

You can use a regular expression to find it:

var str = "sure1to3";
var matches = str.match(/(\d+)to(\d+)/);
if (matches) {
    // matches[1] = digits of first number
    // matches[2] = digits of second number
}

Comments

Your Answer

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.