Trying to get the last part of the url in a pretty weird html structure. Don't ask why it's built that way. There is a very good reason behind it.
The html looks like this
<li class="lifilter"><input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
and the js i'm trying to use
$('#Cheeks... label a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = url.split("/");
var finalvar = urlsplit[4];
$(this).addClass(finalvar);
});
edit: damn.. i can only post once every 90 minutes.
here is updated question with updated html
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
and the js code i'm trying to use (from a previous answer)
$('.lifilter').each(function(){
$(this).find(".filtercheck").next('label').find('a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = lasturl.split("/");
console.log(urlsplit);
var finalvar = urlsplit.pop();
console.log('Adding class: ' + finalvar);
$(this).addClass(finalvar);
});
});
OK, so it appears no one here attempted to try the solution here before posting.
First things first cheeks.... This is a tricky ID to find (You have to escape the periods). The label is also not part of the internal html where ID is cheeks..., so we need to find the adjacent element and look the a anchor tag you're looking for.
Here's the code:
$(document).ready(function() {
$('#Cheeks\\.\\.\\.').next('label').find('a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = lasturl.split("/");
console.log(urlsplit);
var finalvar = urlsplit.pop();
console.log('Adding class: ' + finalvar);
$(this).addClass(finalvar);
});
});
And here is a working jsfiddle with the solution.
keeping it simple like your code you'd do
finalvar = urlsplit[urlsplit.length-1];
in case you don't want the base url as a valid return then:
finalvar = ( urlsplit.length > 1 ? urlsplit[urlsplit.length-1] : "" );
replace "" with your preferred error/default return
you could also try to find the index of the last '/' and do a substring.
try this.
FIDDLE DEMO
var URI = 'www.example.com/sub1/sub2/sub3/',
parts = URI.split('/'),
lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();
//RESULT : "sub3"
You can extract the last section of a path (i.e. everything after the last /) by using a regular expression:
text.replace(/.*\//g, "")
This will remove all of the text before a slash, as well as the slash itself. You'll also notice that your selector wasn't matching any elements; you're looking for labels nested within inputs, which doesn't match the html you posted (and isn't a valid DOM structure). An appropriate selector would be .lifilter label a, since the <label> is within the <li>.
$(function() {
setTimeout(function() {
$('.lifilter label a').each(function() {
// strip everything up to and including the last forward slash
var path = $(this).attr('href').replace(/.*\//g, "");
$(this).addClass(path);
});
}, 1500);
});
a.cheeks:after {
content: " (className = 'cheeks')";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
if you want the last section of url for example activation code or id.You can try this.
var url = 'www.abc.com/code=12345',
parts = url.split('='),
lastPart = parts.pop()
//lastPart = 12345
Related
When search any text on search box, it can be find and highlighted the correct text, but when search next/new text, it's unable to find the next/new text, it's not working when search again, i'm unable to find the issue. The JS below.
JS
$('button#search').click(function() {
var page = $('#ray-all_text');
var pageText = page.html().replace("<span>", "").replace("</span>");
var searchedText = $('#searchfor').val();
var theRegEx = new RegExp("(" + searchedText + ")", "igm");
var newHtml = pageText.replace(theRegEx, "<span>$1</span>");
page.html(newHtml);
$('html, body').animate({
scrollTop: $("#ray-all_text span").offset().top }, 2000);
});
HTML
<div class="ray-search">
<div class="field" id="ray-search-form">
<input type="text" id="searchfor" placeholder="what are you searching for?" />
<button type="button" id="search">Press to Find!</button>
</div>
</div>
<article id="ray-all_text">
<p>
This manual and web site, all information and data and photos contained herein, are the s...
</p>
</article>
Please check the live Example: https://jsfiddle.net/gaezs6s8
Why is this happening? Is there a solution?
My suggestion is to make a few validations before change all the .html() inside the text you want to avoid unexpected behaviors and improve the functionality.
First make a validation to avoid the 'space' as the first value on the input, this will let us later check if the input has a real value inside.
$('body').on('keydown', '#searchfor', function(e) {
if (e.which === 32 && e.target.selectionStart === 0) {
return false;
}
});
Code from this answer
Now Please check the comments on your code:
//Create some vars to later check for:
//['text you are searching', 'number of highlights','actual highlight']
var searching,
limitsearch,
countsearch;
$('button#search').click(function() {
var searchedText = $('#searchfor').val();
var page = $('#ray-all_text');
//Now check if the text on input is valid
if (searchedText != "") {
//If the actual text on the input is different from the prev search
if(searching != searchedText) {
page.find('span').contents().unwrap();
var pageText = page.html();
var theRegEx = new RegExp("(" + searchedText + ")", "igm");
var newHtml = pageText.replace(theRegEx, "<span>$1</span>");
page.html(newHtml);
//Set your variables to the actual search
searching = searchedText;
limitsearch = page.find('span').length;
countsearch=0;
} else {
//If it's the same of the prev search then move to next item instead of repaint html
countsearch<limitsearch-1 ? countsearch++ : countsearch=0;
console.log(countsearch+'---'+limitsearch)
}
//Go to target search
$('body').animate({
scrollTop: $("#ray-all_text span").eq(countsearch).offset().top - 50},
200);
} else {
alert('empty search')
}
});
JqueryDemo
I'm building a widget that will generate a graph for an element when it is double clicked on the page. Without remaking all widgets this is the only way for me to tackle the problem.
I want find the ID of a widget from the html of an element.
All widgets I want to work are inside a div element panel_content_id_#
I want to find the number found on the line of code
var io_id=32715;
How can I search the string for this pattern and get the number (32715).
$('div[id^="panel_content_id_"]').dblclick(function(e){
console.log($(this).attr('id'));
var code = $(this).html();
// Find ID
var id = -1;
var search = code.match("var io_id=");
if(search > -1){
}
console.log($(this).html());
});
The line of code im looking for will look like so
var io_id=xxxxx;
Where xxxxx = some random number I dont know
I want to find xxxxx
Split it in two parts - All the code before the var io_id= and the other part is after that.
And then you know that the line ends with ;, so from that second part you cut of the stuff that is before the semicolon.
CODE
$('div[id^="panel_content_id_"]').dblclick(function(e){
console.log($(this).attr('id'));
var code = $(this).html();
// Find ID
var id = -1;
if (code.indexOf("var io_id")>-1) {
id = parseInt(code.split("var io_id=")[1].split(";")[0]);
}
if(search > -1){
console.log("The code betrayed me");
}
console.log("The id is: " +id);
});
Maybe you could try this regex pattern:
\d+(?! var io_id=)
Used like this:
$('div[id^="panel_content_id_"]').dblclick(function(e) {
console.log($(this).attr('id'));
var code = $(this).html();
// Find ID
var id = -1;
var search = code.match("var io_id=");
if (search) { // Edited
// New code
alert(code.match(/\d+(?! var io_id=)/gim));
}
console.log($(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="panel_content_id_32715">
Div content
<br><br>
var io_id=32715;
</div>
I'd like to be able to target (and then remove) this string of text:
[UPLOAD]any-possible_FILEname.ANY[/UPLOAD]
HTML:
var filenameRegex = new RegExp("\w\d\.");
$('.posts').contents().filter(':contains([UPLOAD])').filter(':contains([/UPLOAD])').filter(function() {
return filenameRegex.test($(this).text());
console.log('yep');
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="posts">
This is a forum post with lots of blabbing in it.
[UPLOAD]this-is-a-random-unknown-filename.jpg[/UPLOAD]
(Note the above always begins with [UPLOAD] and ends
with [/UPLOAD]. Also note that between these 'tags'
is 1 filename of some kind, such as an image or audio
or text file)
</span>
Thanks, much obliged.
var filenameRegex = /\[UPLOAD][\w\.\-]+\[\/UPLOAD]/gi;
$('.posts').filter(':contains([UPLOAD]):contains([/UPLOAD])').filter(function(i,e) {
return filenameRegex.test($(e).text());
}).each(function(i,e){
$(e).text($(e).text().replace(filenameRegex,''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="posts">
This is a forum post with lots of blabbing in it.
[UPLOAD]this-is-a-random-unknown-filename.jpg[/UPLOAD]
(Note the above always begins with [UPLOAD] and ends
with [/UPLOAD]. Also note that between these 'tags'
is 1 filename of some kind, such as an image or audio
or text file)
</span>
The regex you need is:
/\[UPLOAD\](.*)\[\/UPLOAD\]/gi
So your code should be like:
var filenameRegex = new RegExp("/\[UPLOAD\](.*)\[\/UPLOAD\]/gi");
$('.posts').contents().filter(':contains([UPLOAD])').filter(':contains([/UPLOAD])').filter(function(){
return filenameRegex.test($(this).text());
console.log('yep');
}).remove();
Not a regular expression, but this seems to do the trick:
var text = 'hello [UPLOAD]very[/UPLOAD] [UPLOAD]cruel[/UPLOAD] world';
var start = '[UPLOAD]';
var end = '[/UPLOAD]';
var index = text.indexOf(start);
while (index > -1)
{
var end_index = text.indexOf(end);
var removed_text = text.substring(index, end_index + end.length));
text = text.substring(0, index) + text.substring(end_index + end.length);
index = text.indexOf(start);
}
FIDDLE Example
I'm learning how to append all the data attributes from div.query elements to a url string: http://web.com?get=
With the script I can get this result:
"http://web.com?get=|Africa|Asia|Europe"
But is there any way not to have the first one coupled with "|" so that the url should be
"http://web.com?get=Africa|Asia|Europe"
I want to get that result because either http://web.com?get=|Africa|Asia|Europe
or http://web.com?get=Africa|Asia|Europe| would be invalid. Any suggestions?
JS:
$( document ).ready(function() {
$(".query").each(function() {
var div_terms = $(this).data('term'),
source = $('#main').data('source');
var x = source+'|'+div_terms;
$('#main').data('source',x);
$('.result').html(x);
});
});
HTML:
<div id="main" data-source="http://web.com?get="></div>
<div class="query" data-term="Africa"></div>
<div class="query" data-term="Asia"></div>
<div class="query" data-term="Europe"></div>
<div class="result"></div>
The easiest way is to pull all the countries to an array and join them using the pipe character.
var terms = $('.query').map( function() {
return $(this).data('term');
}).get().join('|');
var source = $('#main').data('source');
$('.result').html( source + terms );
Demo
http://jsfiddle.net/cHtT6/3/
You just need to replace the first '|' in the resulting url with an empty character ''.
Make it simple use javascript join function
$( document ).ready(function() {
var terms=[];
$(".query").each(function() {
var div_terms = $(this).data('term');
terms.push(div_terms);
});
var x = $('#main').data('source')+terms.join("|");
$('.result').html(x);
});
Fiddle here
Use an if statement to check if it's the first 'data-term'. If it is then don't use the | character. Then in the else statement you just do as you've already done
DEMO
Just Check whether end is reached like this:
$( document ).ready(function() {
var i=0;
$(".query").each(function() {
i++;
var div_terms = i==$(".query").length? $(this).data('term')+"":$(this).data('term')+"|",
source = $('#main').data('source');
var x = source+''+div_terms;
$('#main').data('source',x);
$('.result').html(x);
});
});
Here when last term is reached. Automatically only "" is appended in all other cases "|" is appended.
For example I've got the simple code:
<ul class="list">
<li>Download file 01</li>
<li>Download file 02</li>
</ul>
and I wish to store in variables only the file names: file01.pdf and file02.pdf, how can I cut them?
Many thanks for the help.
Cheers.
use
lastIndexof and substring
Give anchor tag an id
var elem = document.getElementById ( "anch1" );
elem.href.substring (elem.href.lastIndexOf ( '/' ) + 1 );
Using jQuery
$(function() {
$("ul.list li a").each ( function() {
alert ( $(this).attr ( "href" ).substring ($(this).attr ( "href" ).lastIndexOf ( '/' ) + 1 ) )
});
});
Though you don't have them in this case, in general you would want to strip off the ?search and #hash parts before looking for the last slash to get the file's leafname.
This is very easy using the built-in properties of the link object like pathname instead of processing the complete href:
var a= document.getElementById('link1'); // or however you decide to reference it
var filename= a.pathname.split('/').pop(); // get last segment of path
var fileNames = new Array();
$('.list a').each(function(i, item){
fileNames.push(this.href.substring(this.href.lastIndexOf('/') + 1))
});
This will give you an array of all the filenames, then:
for(var x=0; x<fileNames.length; x++)
{
// Do something with fileNames[x]
}
var myFilename = [];
$("ul.list li a").each(function() {
var href = $(this).attr('href');
var idx = $(this).attr('href').lastIndexOf('/');
myFilename.push((idx >= 0) ? href.substring(idx+1) : href);
});
Here another way:
var arr = [];
$("ul.list li a").each (function(){
arr.push( (this.href.match(/\/[^\/]+$/)[0] || '').substr(1) );
});
var files = $('a[href]').map(function() {
return this.pathname.match(/[^\/]*$/)[0];
});
a[href] will exclude anchors without hrefs (such as named anchors), and pathname will remove query strings and fragments (?query=string and #fragment).
After this, files will contain an array of filenames: ['file01.pdf', 'file02.pdf'].