1

Is it possible to get numbers within brackets from string with RegEx? For example, I have selects with content like:

<select class="selectoption">
    <option value="1">no numbers</option>
    <option value="2">3 (+110.0 грн.)</option>
    <option value="3">Blabla (+95.5 грн.)</option>
</select>

I need to get only numbers, when user select option with brackets (110 or 95.5).

Now I have:

$('.selectoption').change(function() {
    if ( $("select option:selected").text().match(/\(.*\)/).length ){}
        alert (
            $("select option:selected").text().match(/\(.*\)/)
        );
    end
});

But it returns (+110.0 грн.) :(

1
  • live is deprecated. Just so you'll know. Commented Nov 9, 2012 at 12:00

3 Answers 3

4

try:

$('.selectoption').on('change', function () {
  var m = $(this).find(':selected').text().match(/\(.*?([\d.]+).*?\)/);
  console.log(
    m && m[1] || 'n/a'
  ); 
});

http://jsbin.com/ekanog/1/

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

1 Comment

+1, I'd post /\(\D*(\d+?(?:\.\d+)?)\D*\)/ as an answer but your regex looks much more cleaner.
2

Match returns array of char group which you defined in regexp. You can use replace instead match

  $("select option:selected").text().replace(/^(.*)\([^\)\d]*(\d+\.\d+)[^\)\d]*\)$/, '$2')

1 Comment

Thanks... I'm not familiar with regex. It returns +110.0 грн., but I don't need + and ` грн.` :)
1

Should look something like that:

$('form').on('change', '.selectoption', function() {
    var content = $('option:selected', this).text(),
        matches = content.match(/\([^\d]*(\d+(\.\d*)?)/);
    if (matches.length) {
        alert(matches[1]);
    }
});

form being one of .selectoption parents, change the selector if it is uncorrect.

Incase you don't need delegation you can use:

$('.selectoption').on('change', function() {

As you did on your edit. It's works all the same :)

Example Code

4 Comments

Thanks! But one more thing... (+100 грн.) => 100, but (+99.5 грн.) => 99 (without .5) :-[
That's what it does. Look at the code example I've added. (Unless you wanna keep the fraction?)
Fixed it to take fractions too.
Works now! Unfortunately, I can't accept more answers, but it's nice variant, thanks!

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.