Reputation: 110
I'm using jQuery to echo the page title inside a span tag. This works fine, except every page has the site title and page title within the title tag. How can I remove this and simply have the page title?
Ex: Superlong Sites' Title - About Us should be: About Us
My Code:
jQuery(document).ready(function() {
var href = jQuery(location).attr('href');
var url = jQuery(this).attr('title');
jQuery('#current_url').html(url);
$('span#current_url').each(function() { // <---the code in question
console.log($(this).text());
var text = $(this).text().replace('Superlong Site\'s Title- ', '');
$(this).text(text);
});
});
Thanks!
Upvotes: 0
Views: 2506
Reputation: 16359
Split the text into an array based on the dash, then get the last item in the array:
console.log($(this).text());
var text = $(this).text().split('-');
$(this).text(text[text.length-1]);
You can trim the spaces in the front as well, if needed.
Edit - If you want it to be a little faster, you can use RegEx replace (thanks f00bar):
$(this).text($(this).text().replace(/^[^-]+- ?/,''));
If you are comfortable with RegEx this is faster, but if not then you might consider the other option as it is more explicit and maintainable.
Upvotes: 2
Reputation: 3788
This code snippet should help you :)
var url = jQuery(this).attr('title');
var shortUrl = url.substring(url.indexOf("- ") + 1, url.length);
jQuery('#current_url').html(shortUrl);
Upvotes: 1
Reputation: 144669
That's because your replace
function doesn't find the desired string, your title is Superlong Sites' Title -
and you are trying to replace Superlong Site's Title-
.
$(document).ready(function() {
$('#current_url').text(function(){
return $('title').text().replace("Superlong Site's Title - ", '');
})
});
Upvotes: 1