Javascript string comparison issue with backslash - javascript

So I am writing a jquery selector for custom data-xx attribute. What I have as value for this attribute is network path. In my script I am trying to identify the which was clicked by using value of this attribute in my selector
here is code layout
<a data-path="\\network\Dir1\SubDir\SubDir2\file.xml" href="#">Link1</a>
and this is my selector which returns nothing.
$('a[data-path="\\\\network\\Dir1\\SubDir\\SubDir2\\file.xml"]')
only time my selector works is when I just use file name
$('a[data-path*="\file.xml"]')
I am not sure if there is something wrong with the way am escaping backslash here or in the way am using custom attribute selector.
If I do $('a#id').data('path') i get this
"\network\Dir1\SubDir\SubDir2\file.xml"
thanks

As stated in your question comments, you need to use 4 backslahes per backslash in the path:
var allLinks = $('a');
var longLink = $('a[data-name="\\\\\\\\network\\\\Dir1\\\\SubDir\\\\SubDir2\\\\file.xml"]');
console.log(" *** links found: ", allLinks.length, longLink.length);
Here is a working example: http://plnkr.co/edit/D2w8G7yTaOusG5qwT51x?p=preview

$('a[data-path="\\\\\\\\network\\\\Dir1\\\\SubDir\\\\SubDir2\\\\file.xml"]')
this can be worked , but i don't know it's theory exactly.

this is what i did eventually. First comment resolved it for me.
var path = 'value in html';
path.replace(/\\/g, '\\\\');
$(a'[data-path*="' + path+ '"]');

Related

jQuery selector using regex (or something else)

I need to select an attribute in my code that match a string+number in the class name, using jQuery
What I need to do is to match something like that:
var myVar = 'item';
$('#id [class="'+myVar+'\d+"]');
My code contain other classes starting by "item" as well, so I can't use the selector class^="item"
I found out different things on Internet, but nothing that match perfectly my requirement.
I found the jQuery extension ":regex" but I'm not allowed to use it. http://james.padolsey.com/javascript/regex-selector-for-jquery/
I found the use of "filter" as a function but this is horrible for the performance
jQuery filter selector, is this right?
I tried to do something but it's not even working:
$('#id *').filter(function() {
return this.className.match("/"+myVar+"\d/");
});
Do you have some better suggestions?
Thanks.
No you can't use \d with CSS/jQuery selectors.
I suggest you split the number out into another attribute like data-number or something. This way you can target the class easily and efficiently and still have the number available.
<span class="my-class" data-number="1"></span>
<span class="my-class" data-number="6"></span>
<span class="my-class" data-number="10"></span>
jQuery example
$.each($('my-class'), function () {
$(this).attr('data-number');
});
As #Asad mentions they can also be selected using $('.my-class[data-number="1"]').
How about:
$('#id [class*=' + myVar + ']').filter(function() {
return this.className.match(new RegExp('(^|\\s)' + myVar + '\\d+(\\s|$)'));
});
Check jsfiddle demo here.
The selector picks every descendant element of #id with myVar in a class name. Finally it filters them, leaving only those who have myVar followed by one or more of digits as the name of one of its classes.
Note: You probably aready know that, but it is worth warning anyway: you must prevent myVar from having chars with special meaning to selectors (which would mess the [class*=' + myVar + ']' selector) and to regexes (such as the string '[a-z]', which would make the regex match a range instead of the literal '[a-z]' -- in this case, it should be escaped, as '\[a-z\]').

What does this javascript regular expression code do in dealing with URLS?

I am looking at someone elses codebase and I as a javascript noob and doubly so a regular expression noob I can't figure out what the following lines do:
var url = sel.anchorNode.parentNode.href;
var match = self.location.href.replace(/\/$/i, '');
var replaced = url.replace(match,'');
I read it as:
set the var url to the href value of the parent node of the currently selected node
sets the var match to the browsers current URL with the trailing '/' removed (if it exists)
sets the var replaced to the string returned in 1. with the string returned in 2. removed from it
If I am reading it correctly I just can't figure out how it would ever do anything. There isn't any situation, I can think of, where the parent node of a currently selected node would have an href value pointing to the current URL.
So I think I am reading it incorrectly.
Because the href property of an anchor is a fully-resolved URL (even if the href attribute is relative), what that does is remove the current page's path and get you back to a relative URL. E.g., on the page:
http://example.com/foo/bar/
with a link like
...
...you get the href from the anchor which is:
http://example.com/foo/bar/nifty.html
...and then remove http://example.com/foo/bar from it, giving you:
/nifty.html
In this case, of course, that's probably not what you actually want. :-) I have to admit I fail to see how the code is useful, out of context, but then context is king sometimes...

what this replace function do?

I came across some javascript code like this:
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '')
And I don't quite understand what the replace part do.Can someone explain that in detail?
Thanks,G
It replaces selector variable using RegEx.
/.*(?=#[^\s]*$)/ replaces anchor to empty string and perhaps return domain name of page where you in. For example http://example.com/text.php
I've made and example http://jsfiddle.net/9j5Sn/

REGEX / replace only works once

I'm using REGEX and js replace to dynamically populate a variable in a href. The following code works the first time it is used on the page, but if a different variable is passed to the function, it does not replace ANYTHING.
function change(fone){
$("a[href^='/application']").each(function(){
this.href = this.href.replace(/device=.*/,"device="+ fone);
});
}
The problem is that this.href actually returns a full absolute URL. So even your HTML is <a href="/foo"> the .href property will return http://mydomain.com/foo.
So your href attributes is being populated with a full absolute URL, and then the a[href^='/application'] selector doesn't match anymore, because the href attribute starts with the domain name, instead of /application.
.href returns a fully qualified URL, e.g. `http://www.mydomain.com/application/...'. So the selector doesn't work the 2nd time around since your domain relative URL has been replaced with a full URL, and it's looking for things that start with "/application".
Use $(this).attr('href').replace... instead.
Fiddle here: http://jsfiddle.net/pcm5K/3/
As Squeegy says, you're changing the href the first time around so it no longer begins with /application - the second time around it begins with http://.
You can use the jQuery Attribute Contains Selector to get the links, and it's probably also better practice to use a capture group to do the replacement. Like so:
$("a[href*='/application']").each(function(){
this.href = this.href.replace(/(device=)\w*/, "$1" + fone);
});
You'll need to add the g flag to match all instances of the pattern, so your regular expression will look like this:
/device=.*/g
and your code will look like:
this.href = this.href.replace(/device=.*/g,"device="+ fone);
The reason is that unless all you links start as "/device=." the regex wont work.
you need to use /.*device=.*/
the lack of global flag is not the problem. its the backslash in your pattern.

get query string into js/jquery

i hae a link like ( domain.com/jsapi?key=123456 )
hov can i get this "key" into my JS code? i use jQuery and i don't know about its are easy way to get this "key" into JS variable.
tanks for all.
This plugin might helps: jquery url parser
key = $.url.setUrl($(yourlink).attr('href')).param('key');
(not tested)
It's not jquery. It's pure javascript. You can use regexp.
str = "domain.com/jsapi?key=123456" # Take it from wherever you want
splitted = str.split(/\?key=([0-9]+)/)
Then you'll have an array in the "splitted" variable, it's second element (at the id 1) containing the value.
jQuery not needed. The query string is available from the DOM:
window.location.search.match(/key=([^&]*)/);
Which gives you an array that has your value in it.
You can use the URL constructor as follows:
let url = new URL('https://example.com/jsapi?key=123456');
console.log(url.searchParams.get('key')); // Outputs 123456
Using this method you can parse and get any part of a URL.
Important:
Note that I've added the protocol (https://) to the sample URL so I make sure it is a valid URL and it can be parsed.
Take into account the browser compatibility. You can check it here
For more details you can also the the specification.

Categories

Resources