简体   繁体   English

添加空格,保留HTML标记

[英]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. 我有一个字符串,我想检查它的单词是否大于或等于15个字符。 If so, split that word to 5 chars by blank spaces, then return the same string with splitted words. 如果是这样,请将该单词拆分为5个字符,并用空格分隔,然后返回包含拆分单词的相同字符串。

My code works but the problem is that my string could also contain HTML tags and I would like to not touch them. 我的代码可以工作,但是问题是我的字符串也可以包含HTML标记,我希望不要碰它们。

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. 只需检查该部分是否以<开头,那么它就是HTML标记。

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. 编辑:更正了错误(旧答案仅影响html标签),并添加了用于打开和关闭标签的检查。

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;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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