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

Get string inside square brackets with javascript/Jquery

本文关键字:字符串 方括号 获取 javascript Jquery 使用      更新时间:2023-09-26

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

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]。

我想将输入与选项映射。知道吗?

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

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