javascript 不计算空格的 substr 字符

javascript substr chars without counting spaces

我有一个 css 的

文本描述
white-space: pre-wrap;

它包括空格和换行等...

我想在不计算空格的情况下限制描述中的字符数:

description = description.substr(0,100);

当然我需要保留描述格式。

我该怎么做?

您需要遍历字符串的所有字符,并计算所有不是空格的字符(或您想要的任何模式),一旦达到限制,您就知道必须在何处截断字符串:

var description = '1 2 3 4 5 6 7 8 9 10 11 12 13 14'

function limitLength(str, length, exclude) {
  var i = 0
  for (var count = 0 ; i < str.length && count < length; i++) {
    if (!str[i].match(exclude)) {
      count++
    }
  }
  
  return str.substr(0, i)
}

description = limitLength(description, 15, /([\s])/)

console.log(description)

另一种不使用正则表达式的方法是,你可以在删除空格后计算数字

description.replace(' ', '').substr(0, 100)

试试这个功能。这个 returns 正是想要的值:

function mySubstr(a/*description*/, c/*count*/){
    var l=0, dif=0, p=c, 
          dt=[a.substr(0, c)];
    while((l=dt.join("").replace(/\s/g, "").length)<c){
         dt.push(a.substr(p, dif=c-l));
         p+=dif;
    }
    return dt.join("");
}
console.log(mySubstr("1    2 $- 8 58 9&8 85 0j g fg hc 6 4 34 8", 16));

check result online!


添加部分(方法 2 - 更新版本):

你可以试试这个。这个版本也支持多 \s:

function Substr2(desc, c/*count*/){
    var r="", s=0, m=0, res, ok;
    desc.replace(/(.+?)(\s+)/g, function(a,b,d){
        if(ok) return;  
        m+=b.length;
        r+=a;
        res=r.substr(0, m+s-(m-c));
        if(m>=c) ok=1;
        s+=d.length;
    });
    return res;
};

console.log(Substr2("1 2 $- 8 58 9&8 85 0j g fg hc 6 4 34 8", 16));

也许这可以解决您的问题:

let description = "Lorem Ipsum Dolor Sit Amet Consectetur Adipisicing Elit Sed Do Eiusmod Tempor Incididunt Ut Labore Et Dolore Magna Ali";
let spaceCount = ((description || '').match(/\s+/g) || []).length;
let description1 = description.substr(0, 100 + spaceCount);
// OR
let description2 = description.substr(0, 100 - spaceCount);
console.log(description1, description2)

我使用 countable.js 库来执行此操作,顺便说一下,它是根据无聊的按键点击次数计算的。

您只需将其添加到您的 html 页面上,作为 javascript link

<script src="https://cdnjs.cloudflare.com/ajax/libs/countable/3.0.1/Countable.js"></script>

这里有link下载countable.js

https://github.com/RadLikeWhoa/Countable

这是它可以做什么的例子

https://sacha.me/Countable/

这里是一个 link 的实现示例:

https://www.jqueryscript.net/form/Simple-Live-Character-Counter-with-Javascript-Countable.html

使用起来非常简单,你只需要在你要计算的元素旁边添加计数,勾选选项避免空格、点、逗号等。

希望我的 post 能帮到您

祝你好运