what this replace function do? - javascript

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/

Related

Javascript string comparison issue with backslash

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+ '"]');

Array check element ID with wildcard in if statement

I can check an object ID in a array with
if (obj[0].id != "myID")
I would like to do the same with a wildcard, so that
if (obj[0].id != "myID*")
will exclude #myID1, #myID2, #myID3 etc.
I have to stay inside the if statement for this check, I can't call an external function.
If it is not possible, I can use obj[0].className instead of .id :
if (obj[0].className != "myClass")
but every object has several classes in addition of myClass.
jQuery is allowed although I'm not sure it will help.
If you're using jQuery (you've added the tag), why not use the selectors?
$('*:not[id^="myID"]')
This gets all the elements where the attribute does not start with myID. You can use this in your if statement like so:
if($(obj[0]).is('[id^="myID"]'))
First of all, you can definitely use an id attribute selector like this
if(!$(obj[0]).is("[id^=myID]"))
However, why not assign a class to all those elements instead? That sounds like a much more reasonable approach, allowing
if(!$(obj[0]).hasClass("myClass"))
Using String.prototype.indexOf might be one possible approach:
if (obj[0].id.indexOf('myID') !== 0) {
// ID does not start with 'myID'
}
You can even use regular expressions:
if( !/(myId)/g.test( obj[0].id.indexOf('myID') ) ) {
}
I can suggest you this really good playground to test you regexp:
http://lea.verou.me/regexplained/
And this talk:
http://www.youtube.com/watch?v=EkluES9Rvak
Regular expression can be very powerful. Maybe your case is not that hard to be managed with other tecniques but you would find regular expressions reeeally useful in the future for other problems.
You could check that the first 4 characters are myID with .substring():
if(obj[0].id.substring(0,4) != 'myId'){ }
If you wanted to use jQuery it would be really easy to check the id or class:
if(!$(obj[0]).is('[id^=myId]')){ }
or
if(!$(obj[0]).hasClass('myClass')){ }

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\]').

strip a div and all child elements from a string with JavaScript replace RegEx

I have a block of HTML stored in a variable called address_form, within that block of HTML I want to remove, or replace, a portion of it. The part I want to replace is a div with an ID of address_container.
There's clearly something wrong with my RegEx here that i'm using with the replace function as it is not working:
var tempStr = address_form.replace('/\<div id=\"#address_container\"\>.*<\/div\>/', '');
I simply want to replace a string, within a string.
Since you've tagged your question with jQuery, then I would suggest you use jQuery to do this task. Something like:
var tempStr = jQuery(address_from).remove('#address_container').html();
Don't do that, just get the contents of the div and replace the parent of that div with the contents.
So
var tempStr = $('#address_container').html(); // or text()
$('#parent_of_address_container').html(tempStr);
Your regex is wrong. Use this instead:
address_form.replace(/<div id=["-]#address_container["-]>.*<\/div>/,'');
From #RidgeRunner
Correctly matching a DIV element, (which itself may contain other DIV
elements), using a single JavaScript regex is impossible. This is
because the js regex engine does not support matching nested
structures.

javascript regular expression

I want to match some links from a web content. I know I can use file_get_contents(url) to do this in php. How about in javascript?
For regular expression, like
contents
How can I use js regular expression to match this (match only once, do not greedy). I try to use this
/^\<a href=\"someurl\/something\" id=\"someid\"\>(+?)\<\/a\>$/
but it doesn't work.
Can someone help?
Thanks!
You should know that parsing HTML with regex is not the optimal way to solve this problem, and if you have access to a live DOM of the page, you should use DOM methods instead. As in, you should use
document.getElementById('someid').innerHTML // this will return 'contents'
instead of a regex.
I'd highly recommend using a library like jQuery to get the element, and then get the contents via a .text() call. It's much more simple and reliable than trying to parse HTML with regex.
DOM and jQuery suggestions are better but if you still want to use regex then try this:
/^<a href=".*?" id=".*?">(.*?)<\/a>$/
You might as well create the elements with jQuery
var elements = $(html);
var links = elements.find('a');
links.each(function(i, link){
//Do the regexp matching in here if you wish to search for specific urls only
});
In bigger documents, using the DOM is way quicker than regexping the whole thing as text.
Try this~
try {
boolean foundMatch = subjectString.matches("(?im)<a[^>]*href=(\"[^\"]*\"|'[^']*'|[^\\s>]*)[^>]*>.*?</a>");
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
Match double quotation marks,single quotes and empty.
contents
<a href='someurl/something' id='someid'>contents</a>
<a href=someurl/something id=someid>contents</a>

Categories

Resources