简体   繁体   中英

Add blank spaces leaving HTML tags

I have a string that I want to check if it has words longer than or equal to 15 chars. If so, split that word to 5 chars by blank spaces, then return the same string with splitted words.

My code works but the problem is that my string could also contain HTML tags and I would like to not touch them.

function space_that(_e){

    var w = [];
    var t = $(_e).text();

    w = t.split(" ");

    for(var s in w)
        if(w[s].length >= 15)
            w[s] = w[s].substr(0,10) + " ";

    $(_e).text(w.join(" "));

    return true;

}

Just check if that part begins with an <, then it is an HTML tag.

function space_that(_e){

    var w = [];
    var t = $(_e).text();

    w = t.split(" ");

    for(var s in w) {
        if(w[s].length >= 15 
           && w[s].substring(0, 1) != "<" 
           && w[s].substring(w[s].length-1, 1) != ">")
            w[s] = w[s].substr(0,10) + " ";
    }

    $(_e).text(w.join(" "));

    return true;

}

Edit: Corrected mistake (old answer affected ONLY html tags) and added check for opening and closing tags.

Following version should work for tags with space inside.

function space_that(_e){

    var w = [];
    var t = $(_e).text();

    w = t.split(" ");
    var inTag = false;

    for(var s in w) {
        if(w[s].substring(0, 1) == "<") inTag = true;
        if(w[s].substring(w[s].length-1, 1) == ">") inTag = false;
        if(inTag) continue;
        if(w[s].length >= 15 
           && w[s].substring(w[s].length-1, 1) != ">")
            w[s] = w[s].substr(0,10) + " ";
    }

    $(_e).text(w.join(" "));

    return true;

}

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