4

How do I split selected value, seperate the number from text in jQuery?

Example:

myselect contains c4

Just get only the number 4.

$('select#myselect').selectToUISlider({
      sliderOptions: {
        stop: function(e,ui) {
          var currentValue = $('#myselect').val();
          alert(currentValue);
          var val = currentValue.split('--)
          alert(val);

        }
      }
    });
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
user683742
  • 80
  • 2
  • 8
  • Please use a meaningful, relevant title. – SLaks Sep 01 '11 at 14:57
  • There's a syntax error in the line above the last alert. Your second hyphen should be the ending single quote mark. With that said, is the value actually "c-4" rather than "c4" as you had said? If not, why are you splitting on '-'? – CashIsClay Sep 01 '11 at 14:58

3 Answers3

11

You can use regex to pull only the numbers.

var value = "c4";
alert ( value.match(/\d+/g) );

edit: changed regex to /\d+/g to match numbers greater than one digit (thanks @Joseph!)

Joseph Yaduvanshi
  • 20,241
  • 5
  • 61
  • 69
4

1) if it's always : 1 letter that followed by numbers you can do simple substring:

'c4'.substring(1); // 4 
'c45'.substring(1); // 45

2) you can also replace all non-numeric characters with regular expression:

'c45'.replace(/[^0-9]/g, ''); // 45
'abc123'.replace(/[^0-9]/g, ''); // 123
Dmitry F
  • 1,650
  • 1
  • 15
  • 20
1

If you know that the prefix is always only one character long you could use this:

var val = currentValue.substr(1);
Muleskinner
  • 14,150
  • 19
  • 58
  • 79