简体   繁体   中英

jQuery - how to remove characters inside span tag

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!

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.

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);

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 - ", '');
  })
});

尝试使用.html()函数设置跨度内容。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM