javascript行有待解释

时间:2014-07-21 18:37:58

标签: javascript jquery html

请告诉我们以下代码行的含义

name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");

是什么

name.replace(/[\[]/, "\\[")

完整的功能如下

  function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

它被称为这样,

var getID = getParameterByName('getID');

1 个答案:

答案 0 :(得分:7)

它只是通过将[]分别转换为\[\]来逃避。{/ p>

示例:

name = 'foo [bar] baz';
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
// name is now 'foo \[bar\] baz'