2

我在导航树中有节点。我想选择属于 url 的所有节点,以便突出显示它们。我让它工作但忘记了一个极端情况,即 url 的最后一部分以相同的字符串开头。

在这种情况下,如果有人在 url/products/foobar-super我希望它选择/products/products/foobar-super不是/products/foobar.

describe('part of url', function () {

  it('matches /products and /products/foobar-super', function () {

    var current = '/producten/foobar-super';

    var nodes = [
      '/products',
      '/products/foobar',
      '/products/foobar-super',
    ];

    var result = [];

    nodes.forEach(function (node) {
      if (new RegExp(node + '.*').test(current)) {
        result.push(node);
      }
    });

    result.should.eql([
      '/products',
      '/products/foobar-super',
    ]);

  });

});

Jsfiddle 与测试:http: //jsfiddle.net/RKDga/2/

不确定是否可以使用正则表达式,我猜的另一个解决方案是拆分节点和当前 url/比较它们。

4

3 回答 3

1

以下代码可以帮助您 JSFIDDLE

    /*globals mocha: true, describe: true, it: true, beforeEach:true */
(function() {
    function assert(expr, msg) {
        if (!expr) throw new Error(msg || 'failed');
    }

    mocha.setup({
        ui: "bdd",
        ignoreLeaks: true
    });

    describe('part of url', function () {

      it('matches /products and /products/foobar-super', function () {

        var current = '/products/foobar-super';

        var nodes = [
          '/products',
          '/products/foobar',
          '/products/foobar-super',
        ];

        var result = [];
         ;
    var urllist =  current.split("/");
   var temp; 
    nodes.forEach(function (node) {
       temp = "";
      for(var i=1;i<urllist.length; i++){
            temp += "/"+ urllist[i];
          if(node == temp){
             result.push(node );
          }
      }
    });

 console.log(result);          

        assert(result[0] === '/products', 'first item should be /products');
        assert(result[1] === '/products/foobar-super', 'second item should be /products/foobar-super');


      });

    });


mocha.run();
}());
于 2013-03-17T19:47:45.930 回答
1

这是另一个没有正则表达式的解决方案:

describe('part of url', function () {

  it('matches /products and /products/foobar-super', function () {

    var current = '/products/foobar-super';

    var nodes = [
      '/products',
      '/products/foobar',
      '/products/foobar-super',
    ];

    var result = [];

    nodes.forEach(function (node) {

      var node_parts = node.split('/');
      var current_parts = current.split('/');
      var match = true;

      node_parts.forEach(function (node_part, i) {

        if (node_part !== current_parts[i]) {
          match = false;
        }

      });

      if (match) {
        result.push(node);
      }

    });

    result.should.eql([
      '/products',
      '/products/foobar-super',
    ]);

  });

});
于 2013-03-17T19:52:55.327 回答
1

测试将通过,如果

new RegExp(node + '.*')

改为

new RegExp(node + '(/|$)')

它会阻止匹配,除非node后面跟着/或字符串的结尾。

于 2013-03-17T20:16:58.273 回答