简体   繁体   中英

Regex in jQuery: numbers within brackets

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 грн.) :(

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/

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')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM