jQuery selector using regex (or something else) - javascript

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

Related

jQuery blink(), strike() and bold methods

I am trying to solve a question.
I wrote the following code, and it works fine:
(function () {
if($('#target:contains("bold")')) {
$('#target span:first').css('font-weight','bold');
}
if($('#target:contains("strike")')) {
$('#target span').eq(1).css('text-decoration','line-through');
}
if($('#target:contains("blink")')) {
$('#target span:last').css('text-decoration','blink');
}
}) ();
Their solution is as follows:
(function () {
var target = $('#target');
var html = target.html();
html = html.replace('blink',"$&".blink());
html = html.replace('bold',"$&".bold());
html = html.replace('strike',"$&".strike());
target.html(html);
}) ();
I have the following questions:
I do not understand what is "$&" in "$&".blink(), "$&".bold() and "$&".strike(),
Are blink, bold and strike jQuery UI methods?
These are not jQuery methods. Everything in jQuery is either a function that of the form $.funcName() or a method that operates on a jQuery object, e.g. $(something).methodName().
These are regular Javascript methods of the String class: String.prototype.blink
, String.prototype.bold, String.prototype.strike. They just wrap their argument with the appropriate HTML element. However, they have been deprecated, because CSS is preferred these days rather than the old tags like <blink>, so you shouldn't use them.
"$&" is a feature of the .replace() method, it's automatically replaced with the original matching element. It's mostly useful when using a regular expression, since you don't know the exact string that will match the pattern.
Your solution to the problem doesn't look like it will work properly. It assumes that each word is in its own span, and also that bold is in the first span, strike is in the second span, and blink is in the third span. The objective of the exercise is to find the words wherever they are in the DIV, and put the appropriate style around just that word.
The JavaScript replace() method uses regular expressions. The $& syntax is shorthand for the matched expression; so it will represent blink, bold, and strike respectively.
As #Daniel A. White mentions in his answer, blink(), bold(), and strike() are deprecated methods from string.prototype for wrapping the source string in markup. The exact markup used will vary by browser; for instance, one may return <b>bold</b>, another <strong>bold</strong> and yet another <span style="font-weight: bold">bold</span>.
For what it's worth, while #Barmr's accepted answer is shorter, I find yours more elegant in that it's easy to understand, consistent in its results, and standards-based. That said, #Barmar raises valid concerns regarding the assumptions it makes and, therefore, its usefulness in a general context.
Those are deprecated methods for wrapping a string in a certain element.
String.prototype.blink reveals it to be a native method.
You can view those here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/blink
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/bold
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/strike

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')){ }

Select class name (number) using RegEx & Jquery

I have a element like this
<div class="th-class2 th-hhjjsd th-context-78474378437834873"></div>
(Note: I know class names should not be pure numbers)
I want to get the numerical number from this div.
id = 78474378437834873
Is there a way I can use regular expressions to do it. I am nearly there but it only returns the first 4 numbers.
I use a clickevent to target the div and try and get the class like this
var classString = $(this).prop("class").match(/([0-9]+)/)[1];;
console.log(classString)
result is 7847
I am just not understanding how to get the rest of the number.
Thanks
You shouldn't use integers for class names because using a class typically means you are going to use the element more the once and adding a dynamic number defeats the purpose of classes, also working with someone else code and they use integers it's very hard to understand their code. As far as your questions goes, you shouldn't really use regular expressions to get a value of a class you should either store the value as an id so your element would look like this,
HTML
<div id="78474378437834873" class="th-class2 th-hhjjsd"></div>
or you could use a data object which is how I would do it like so,
HTML
<div class="th-class2 th-hhjjsd" data-object='{"value":78474378437834873}'></div>
and then when you select your element with your click event to get the value of the element you clicked console log the elements data object like so
jQuery
$('.th-class2').click(function() {
console.log($(this).data('object').value);
});
You should not use number only class names, they must start with an Alpha character [a-Z]
You can find what are the allowed characters in this discussion: Which characters are valid in CSS class names/selectors?
(Please make sure to read also the comments).
As per a solution for you,
The easy solution would be to use data attributes as so:
<div data-id="1000"></div>
and then you could get your id as simple as:
$(this).on('click', function() { console.log($(this).data('id')); } );
Happy Coding.

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/

selecting classes using wildcard not exact class name

I have several classes that I want to select .group1-1 .group1-2 .group1-3, each one of these has 50 elements under it.
Is there a way to select all classes that start with group1 (so I end up selecting group1-1, group1-2, group1-3), something like $(".group1"+*)
You can also use something along the lines of this if you'd like to avoid regex:
$("[class^='group1-']").click(function () {
var groupNumber = $(this).attr('class').split('-')[1];
alert('Yep, you clicked group1-' + groupNumber);
});
Example here: http://jsfiddle.net/iwasrobbed/7bjtb/
This question discusses jquery wildcard / regex selectors. Which basically allow you to use a regular expression to specify matching classes.

Categories

Resources