patternjavascriptMinor
Regex match for a string in a URL
Viewed 0 times
matchforregexstringurl
Problem
I feel like there is too much repetitive code going on here. All I am doing is doing a basic regex match for a string in the URL.
If a match is found, I find a
However, I feel like there is a more efficient way to code this:
``
If a match is found, I find a
li with a class (.index, .grid or .type) and add the active class. This is just for my main nav in an attempt to make it somewhat dynamic.However, I feel like there is a more efficient way to code this:
$(document).ready(function() {
var myLocation = window.location.href;
var index = /index/i;
var grid = /grid/i;
var type = /type/i;
var urlIndex = convertURL.match(index);
var urlGrid = convertURL.match(grid);
var urlType = convertURL.match(type);
if (urlIndex) {
$('.index').addClass('active');
} else if (urlGrid) {
$('.grid').addClass('active');
} else if (urlType) {
$('.type').addClass('active');
}
});
``
Solution
Much like elclanrs' solution, just slightly more "plain"
$(function () {
var classes = ['index', 'grid', 'type'],
url = window.location.href.toLowerCase();
for(var i = 0, l = classes.length ; i < l ; i++ ) {
if(url.indexOf(classes[i]) !== -1) {
$('.' + classes[i]).addClass('active');
break; // only first matching class is considered
}
}
});Code Snippets
$(function () {
var classes = ['index', 'grid', 'type'],
url = window.location.href.toLowerCase();
for(var i = 0, l = classes.length ; i < l ; i++ ) {
if(url.indexOf(classes[i]) !== -1) {
$('.' + classes[i]).addClass('active');
break; // only first matching class is considered
}
}
});Context
StackExchange Code Review Q#51720, answer score: 4
Revisions (0)
No revisions yet.