最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Javascript extract numbers from a string - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Dec 3, 2011 at 6:35 Sandy505Sandy505 8883 gold badges15 silver badges26 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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).

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
}
发布评论

评论列表(0)

  1. 暂无评论