JQuery join multiple shortcuts
Hi I have a div element that contains a list of checkboxes such as
<ul> <li><input type="checkbox" ID="check1" /><label for="check1">Monday</label></li> <li><input type="checkbox" ID="check2" checked="checked"/><label for="check2">Tuesday</label></li> <li><input type="checkbox" ID="check3" /><label for="check3">Wednesday</label></li> <li><input type="checkbox" ID="check4" checked="checked"/><label for="check4">Thursday</label></li> </ul> I want the values ββto be marked on a tuesday-thursday string. So I wrote this very brief jQuery instruction
$('input:checked', 'ul').next().text() This will give me "TuesdayThursday". I could not find a way to pass the delimiter and have a Tuesday-Thursday.
use begex?
var str =$('input:checked', 'ul').next().text().replace( /([az])([AZ])/g, "$1-$2"); alert(str); the modified fiddle too simply forgot g to handle more than 2
Explaination
please do not want to point out the regex expert, so my explanation may not be 100% accurate.
. replace () is a javascript function that allows you to replace text strings. It may take regular expression
in the example in which I specify the regex is between them // reverse oblique first section
[az] says lowercase letters
in the second part of the regular expression
[az] says top level letters
putting them in parentheses, we want uppercase letters to be entered
then the "g" after says you need to make a global replacement ie after the first set is found, repeat this until you find more
then after regular expression we need to say that we want to replace it like this
$1 and
$2 are the assignments of variables from a regular expression, and we put a hyphen between them to give us the desired result
$(document).ready(function() { var days = $.map($("input:checked"), function(element, index) { return $(element).next().text(); }).join("-"); alert(days); });