简体   繁体   中英

Replacing part of a text using jQuery's .replaceWith function

I am working on a new masterpage withing sharepoint 2010. One of the placeholders produces the sitename - the page name in a string. When the page is ready the sources shows this for exampe.

<h1 class="ribbonmc">
    Devness Squared - Mark Jensen
</h1>

Devenss Squared is the site name and Mark Jensen is the page name. I am trying to remove the sitename from being displayed and show the page name only using jQuery. This is what I have so far.

$(document).ready(function() {
        $('#ribbonmc').text(function(i, oldText) {
            return oldText === 'Devness Squared - ' ? '' : oldText;
        });
    });

Regex solution:

$(".ribbonmc").text(function(i, oldText) {
    return oldText.replace(/^Devness Squared - /, "");
});

Non-regex solution:

$(".ribbonmc").text(function(i, oldText) {
    var r = "Devness Squared - ";
    return oldText.indexOf(r) === 0 ? oldText.substring(r.length) : oldText;
});
$(document).ready(function() {
    var sitename = 'Devness Squared - ';
    $(".ribbonmc").text(function(i, oldText) {
        return oldText.indexOf(sitename) === 0    // if it starts with `sitename`
             ? oldText.substring(sitename.length) // t: return everything after it
             : oldText;                           // f: return existing
    });
});

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