开发者

using javascript variables in javascript regular expressions

开发者 https://www.devze.com 2022-12-13 07:59 出处:网络
I am just getting used to regular expressions and am unsure of how to use JavaScript variables in them.

I am just getting used to regular expressions and am unsure of how to use JavaScript variables in them.

My code is:

if (window.location.hostname == 'localhost') {
    var $sURLDomain = 'http://localhost/';
}
else {
    var $sURLDomain = 'http://mysite.com';
}


$('#content a[href^=$sURLDomain]').addClass('internal');

Essentially I am setting the variable $sURLDomain based on whether I'm on my loca开发者_JS百科l or live url.

I then want to test whether my links starting with the $sURLDomain variable and use jQuery to add a class to those specific links only.

This doesn't seem to be functioning, so am unsure of how to achieve this.


Try this:

$('#content a[href^="'+$sURLDomain+'"]').addClass('internal');

Or:

$('#content a').filter(function() {
    return this.href && this.href.substr(0, $sURLDomain.length) != $sURLDomain;
}).addClass('internal');


$('#content a[href^=$sURLDomain]').addClass('internal');
  1. JavaScript doesn't do PHP-style string interpolation. You have to say '#content a[href^='+sURLDomain+']'.

  2. It's unusual to begin your JavaScript variables with a $. Some people use it as a kind of ‘Hungarian notation’-style flag that the variable is a wrapper object from jQuery or other library. It's arguable whether that's a good idea, but either way don't prefix your variables with $ just because that's what PHP does.

  3. The [^=...] selector checks the start of the attribute value for a literal string. Contrary to the question title, there is no regex here. The only connection to regular expressions is the use of ^ to mean ‘the start of the string’.

  4. If there's a character that's special for selectors in the URL, such as a ] or \, the lack of escaping means the selector expression will break. Probably unlikely in this particular case, but it may well be simpler (and easier to deploy given changing domain names) to say:

    for (var i= document.links; i-->0;)
        if (document.links[i].hostname===location.hostname)
            $(document.links[i]).addClass('internal');
    
0

精彩评论

暂无评论...
验证码 换一张
取 消