简体   繁体   中英

Get string inside square brackets with javascript/Jquery

I have this script to handle a form and preview a background change:

if(!options) {
        var optionsTemp = $manageBackgroundForm.serializeArray();

        var regex =/\bg[[a-z]+\]/;
        $.each(optionsTemp, function(index, options) {
            var test = options.name.match(regex);
            debug(test[0]); // DONT WORK 

        });

        var options = new Object();
        options.color = 'red';
        options.image = 'test.png';
        options.position = '20px 20x';
        options.attachment = 'fixed';
        options.repeat = 'repeat-x';
        options.size = 'cover';
    }

    $('body').css({
        'background-color': options.color,
        'background-image': 'url('+options.image+')',
        'background-position': options.position,
        'background-attachment': options.attachment,
        'background-repeat': options.repeat,
        'background-size': options.size  //contain
     });

My inputs are like input name="bg[color]" . I use it like this to easy handle the form in PHP. But I am having problems handling it in javascript. I want to get all the BG options (and only the bg options) from my form - I have other inputs like val[example].

I want to map the inputs with the options. Any idea?

Here is an explanation of your regex:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
----------------------------------------------------------------------
  g                        'g'
----------------------------------------------------------------------
  [[a-z]+                  any character of: '[', 'a' to 'z' (1 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  \]                       ']'
----------------------------------------------------------------------
)                        end of grouping

I'm sure that isn't what you want.

Try this one instead:

/\bbg\[[a-z]+\]/

Note the b after the word boundary.

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