检查url正则表达式的一部分
Check if part of url regex
我在导航树中有节点。我想选择作为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 with the test: http://jsfiddle.net/RKDga/2/
不确定是否可以使用正则表达式,我想另一个解决方案是将节点和/
上的当前url进行比较。
如果
new RegExp(node + '.*')
改为
new RegExp(node + '(/|$)')
防止匹配,除非node
后面跟着/
或字符串结束。
这里有一个不需要正则表达式的解决方案:
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',
]);
});
});
下面的代码可能会对您有所帮助
/*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();
}());
相关文章:
- 如何获取在Javascript正则表达式中用正斜杠分隔的字符串的一部分
- 如何仅替换以下正则表达式(JavaScript)的一部分
- 使用正则表达式替换字符串的一部分
- 如何在正则表达式中否定类的一部分
- 为什么在 javascript 中将正面回溯捕获为正则表达式匹配的一部分
- 拆分忽略正则表达式的一部分
- 如何使用正则表达式或 jQuery 检索 URL 的最后一部分
- 使用正则表达式拉出字符串的一部分
- 为什么我的正则表达式捕获组只在匹配多个部分时捕获字符串的最后一部分
- 如何仅对字符串的一部分应用正则表达式
- 在 Javascript 中使用正则表达式替换 html 字符串的一部分
- 如果字符串是编号列表的一部分,正则表达式将检测到什么
- 使用正则表达式或javascript提取ID的最后一部分
- 用Javascript正则表达式将字符串的一部分与列表中的项相匹配
- 用什么正则表达式来确定<或比;是HTML标记的一部分
- 正则表达式以避免替换html标记的一部分
- 正则表达式查找模式并只替换其中的一部分
- 如何返回匹配正则表达式的javascript字符串的一部分
- 正则表达式匹配字符串的最后一部分
- 使 JavaScript 正则表达式的一部分可选