使用javascript / Jquery在方括号内获取字符串

时间:2012-08-10 10:29:10

标签: javascript jquery regex

我有这个脚本来处理表单并预览背景更改:

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
     });

我的输入类似于输入名称=“bg [颜色]”。我这样使用它来轻松处理PHP中的表单。但是我在使用javascript处理它时遇到了问题。我想从我的表单中获取所有BG选项(以及只有bg选项) - 我还有其他输入,例如val [example]。

我想用选项映射输入。任何的想法?

1 个答案:

答案 0 :(得分:3)

以下是对正则表达式的解释:

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

我确定这不是你想要的。

试试这个:

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

请注意字边界后的b