直接截断字符串 JavaScript

发布于 2024-08-02 12:06:28 字数 287 浏览 2 评论 0原文

我想使用直接 JavaScript 截断动态加载的字符串。这是一个网址,所以没有空格,而且我显然不关心单词边界,只关心字符。

这是我得到的:

var pathname = document.referrer; //wont work if accessing file:// paths
document.getElementById("foo").innerHTML = "<a href='" + pathname +"'>" + pathname +"</a>"

I'd like to truncate a dynamically loaded string using straight JavaScript. It's a url, so there are no spaces, and I obviously don't care about word boundaries, just characters.

Here's what I got:

var pathname = document.referrer; //wont work if accessing file:// paths
document.getElementById("foo").innerHTML = "<a href='" + pathname +"'>" + pathname +"</a>"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

要走就滚别墨迹 2024-08-09 12:06:28

使用 substring 方法:

var length = 3;
var myString = "ABCDEFG";
var myTruncatedString = myString.substring(0,length);
// The value of myTruncatedString is "ABC"

所以在你的情况下:

var length = 3;  // set to the number of characters you want to keep
var pathname = document.referrer;
var trimmedPathname = pathname.substring(0, Math.min(length,pathname.length));

document.getElementById("foo").innerHTML =
     "<a href='" + pathname +"'>" + trimmedPathname + "</a>"

Use the substring method:

var length = 3;
var myString = "ABCDEFG";
var myTruncatedString = myString.substring(0,length);
// The value of myTruncatedString is "ABC"

So in your case:

var length = 3;  // set to the number of characters you want to keep
var pathname = document.referrer;
var trimmedPathname = pathname.substring(0, Math.min(length,pathname.length));

document.getElementById("foo").innerHTML =
     "<a href='" + pathname +"'>" + trimmedPathname + "</a>"
剩一世无双 2024-08-09 12:06:28

这是您可以使用的一种方法。这是 FreeCodeCamp 挑战之一的答案:

function truncateString(str, num) {
  if (str.length > num) {
    return str.slice(0, num) + "...";
  } else {
    return str;
  }
}

Here's one method you can use. This is the answer for one of FreeCodeCamp Challenges:

function truncateString(str, num) {
  if (str.length > num) {
    return str.slice(0, num) + "...";
  } else {
    return str;
  }
}
一刻暧昧 2024-08-09 12:06:28

更新了ES6版本

const truncateString = (string = '', maxLength = 50) => 
  string.length > maxLength 
    ? `${string.substring(0, maxLength)}…`
    : string

// demo the above function
alert(truncateString('Hello World', 4));

Updated ES6 version

const truncateString = (string = '', maxLength = 50) => 
  string.length > maxLength 
    ? `${string.substring(0, maxLength)}…`
    : string

// demo the above function
alert(truncateString('Hello World', 4));

泅人 2024-08-09 12:06:28

是的,子串。你不需要做 Math.min;索引比字符串长度长的子字符串以原始长度结束。

但!

document.getElementById("foo").innerHTML = "<a href='" + pathname +"'>" + pathname +"</a>"

这是一个错误。如果 document.referrer 中有撇号怎么办?或者在 HTML 中具有特殊含义的各种其他字符。在最坏的情况下,引用者中的攻击者代码可能会将 JavaScript 注入您的页面,这是一个 XSS 安全漏洞。

虽然可以手动转义路径名中的字符来阻止这种情况发生,但这有点痛苦。使用 DOM 方法比摆弄 insideHTML 字符串更好。

if (document.referrer) {
    var trimmed= document.referrer.substring(0, 64);
    var link= document.createElement('a');
    link.href= document.referrer;
    link.appendChild(document.createTextNode(trimmed));
    document.getElementById('foo').appendChild(link);
}

yes, substring. You don't need to do a Math.min; substring with a longer index than the length of the string ends at the original length.

But!

document.getElementById("foo").innerHTML = "<a href='" + pathname +"'>" + pathname +"</a>"

This is a mistake. What if document.referrer had an apostrophe in? Or various other characters that have special meaning in HTML. In the worst case, attacker code in the referrer could inject JavaScript into your page, which is a XSS security hole.

Whilst it's possible to escape the characters in pathname manually to stop this happening, it's a bit of a pain. You're better off using DOM methods than fiddling with innerHTML strings.

if (document.referrer) {
    var trimmed= document.referrer.substring(0, 64);
    var link= document.createElement('a');
    link.href= document.referrer;
    link.appendChild(document.createTextNode(trimmed));
    document.getElementById('foo').appendChild(link);
}
永言不败 2024-08-09 12:06:28

以下代码截断字符串并且不会拆分单词,而是丢弃发生截断的单词。完全基于 Sugar.js 源。

function truncateOnWord(str, limit) {
        var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
        var reg = new RegExp('(?=[' + trimmable + '])');
        var words = str.split(reg);
        var count = 0;
        return words.filter(function(word) {
            count += word.length;
            return count <= limit;
        }).join('');
    }

Following code truncates a string and will not split words up, and instead discard the word where the truncation occurred. Totally based on Sugar.js source.

function truncateOnWord(str, limit) {
        var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
        var reg = new RegExp('(?=[' + trimmable + '])');
        var words = str.split(reg);
        var count = 0;
        return words.filter(function(word) {
            count += word.length;
            return count <= limit;
        }).join('');
    }
笨死的猪 2024-08-09 12:06:28

我想我会提到 Sugar.js 。它有一个非常聪明的截断方法。

来自文档

截断字符串。除非 split 为 true,否则 truncate 不会分割单词,而是
丢弃发生截断的单词。

示例:

'just sittin on the dock of the bay'.truncate(20)

输出:

just sitting on...

Thought I would give Sugar.js a mention. It has a truncate method that is pretty smart.

From the documentation:

Truncates a string. Unless split is true, truncate will not split words up, and instead
discard the word where the truncation occurred.

Example:

'just sittin on the dock of the bay'.truncate(20)

Output:

just sitting on...
沉溺在你眼里的海 2024-08-09 12:06:28

一条线ES6解决方案

如果字符串长度超过给定长度,它不仅会截断字符串,还会添加结束字符串。

const limit = (string, length, end = "...") => {
    return string.length < length ? string : string.substring(0, length) + end
}

limit('Hello world', 5) // Hello...

One line ES6 Solution

Instead of just truncating the string, it also adds an ending string if the string length exceeds the given length.

const limit = (string, length, end = "...") => {
    return string.length < length ? string : string.substring(0, length) + end
}

limit('Hello world', 5) // Hello...
绮筵 2024-08-09 12:06:28

是的,substring 效果很好:

stringTruncate('Hello world', 5); //output "Hello..."
stringTruncate('Hello world', 20);//output "Hello world"

var stringTruncate = function(str, length){
  var dots = str.length > length ? '...' : '';
  return str.substring(0, length)+dots;
};

Yes, substring works great:

stringTruncate('Hello world', 5); //output "Hello..."
stringTruncate('Hello world', 20);//output "Hello world"

var stringTruncate = function(str, length){
  var dots = str.length > length ? '...' : '';
  return str.substring(0, length)+dots;
};
南渊 2024-08-09 12:06:28

要将字符串截断为特定长度,请在 JavaScript 中使用以下单线性箭头函数:

const truncate = (str, len) => str.slice?.(0, len);
    
console.log(truncate("Hello, World!", 5));
// Expected Output: Hello

上面的函数使用 String.prototype.slice 方法,该方法获取字符串的一大块并将其返回为一个新的字符串而不改变原来的字符串。

For truncating a String to a specific length, use the following one-linear arrow function in JavaScript:

const truncate = (str, len) => str.slice?.(0, len);
    
console.log(truncate("Hello, World!", 5));
// Expected Output: Hello

The above function uses the String.prototype.slice method, which takes a chunk of a string and returns it as a new string without changing the original.

Bonjour°[大白 2024-08-09 12:06:28

除了 substring 方法之外,我还为此找到了一个不错的小 JS 库。

它在普通 javascript 中有多种有用的方法来截断字符串

按字符截断:

var pathname = 'this/is/thepathname';
document.getElementById("foo").innerHTML = "<a class='link' href='" + pathname +"'>" + pathname +"</a>"

// call the plugin - character truncation only needs a one line init
new Cuttr('.link', { length: 10 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/cuttr/1.3.2/cuttr.min.js"></script>

<div id="foo"></div>

只需将 class 添加到 a 并初始化插件即可。

多行文本剪辑也是可能的。
github 上的 cuttr.js 文档 中提到了更多选项,例如单词或句子截断页。

Besides the substring method, i found a nice little JS lib for this purpose.

It has mutliple useful methods in vanilla javascript to truncate a string.

Truncation by characters:

var pathname = 'this/is/thepathname';
document.getElementById("foo").innerHTML = "<a class='link' href='" + pathname +"'>" + pathname +"</a>"

// call the plugin - character truncation only needs a one line init
new Cuttr('.link', { length: 10 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/cuttr/1.3.2/cuttr.min.js"></script>

<div id="foo"></div>

Simply add a class to the a and init the plugin.

Multiline text clipping is also possible.
More options like word oder sentences truncation are mentioned in the cuttr.js docs on the github page.

睡美人的小仙女 2024-08-09 12:06:28

您可以借助内部 JavaScript 方法修复此方法

const truncate = (text, len) => {
  if (text.length > len && text.length > 0) {
    return `${text.split(" ").slice(0, len).join(" ")} ...`;
  } else {
    return text;
  }
};

You can fix this method with the help of internal JavaScript methods

const truncate = (text, len) => {
  if (text.length > len && text.length > 0) {
    return `${text.split(" ").slice(0, len).join(" ")} ...`;
  } else {
    return text;
  }
};

樱娆 2024-08-09 12:06:28
var str = "Anything you type in.";
str.substring(0, 5) + "" //you can type any amount of length you want
var str = "Anything you type in.";
str.substring(0, 5) + "" //you can type any amount of length you want
ぇ气 2024-08-09 12:06:28

如果你想按单词截断。

function limit(str, limit, end) {

      limit = (limit)? limit : 100;
      end = (end)? end : '...';
      str = str.split(' ');
      
      if (str.length > limit) {
        var cutTolimit = str.slice(0, limit);
        return cutTolimit.join(' ') + ' ' + end;
      }

      return str.join(' ');
    }

    var limit = limit('ILorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus metus magna, maximus a dictum et, hendrerit ac ligula. Vestibulum massa sapien, venenatis et massa vel, commodo elementum turpis. Nullam cursus, enim in semper luctus, odio turpis dictum lectus', 20);

    console.log(limit);

in case you want to truncate by word.

function limit(str, limit, end) {

      limit = (limit)? limit : 100;
      end = (end)? end : '...';
      str = str.split(' ');
      
      if (str.length > limit) {
        var cutTolimit = str.slice(0, limit);
        return cutTolimit.join(' ') + ' ' + end;
      }

      return str.join(' ');
    }

    var limit = limit('ILorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus metus magna, maximus a dictum et, hendrerit ac ligula. Vestibulum massa sapien, venenatis et massa vel, commodo elementum turpis. Nullam cursus, enim in semper luctus, odio turpis dictum lectus', 20);

    console.log(limit);

沩ん囻菔务 2024-08-09 12:06:28

逻辑如下

  • 获取字符串的长度

  • 如果超过阈值,则获取
    子字符串并以省略号或其他符号结尾

  • 否则,返回输入字符串

    函数 truncateString(str: 字符串, num: 数字, 结尾: 字符串 = '...') {
    返回 str.length >号? str.slice(0, num) + 结尾: str;
    }

The logic will be as follows

  • get the length of the string

  • if it is more than a threshold, get the
    substring and end with ellipsis or other notation

  • else, return the input string

    function truncateString(str: string, num: number, ending: string = '...') {
    return str.length > num ? str.slice(0, num) + ending : str;
    }

已下线请稍等 2024-08-09 12:06:28
var pa = document.getElementsByTagName('p')[0].innerHTML;
var rpa = document.getElementsByTagName('p')[0];
// console.log(pa.slice(0, 30));
var newPa = pa.slice(0, 29).concat('...');
rpa.textContent = newPa;
console.log(newPa)
<p>
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here
</p>

var pa = document.getElementsByTagName('p')[0].innerHTML;
var rpa = document.getElementsByTagName('p')[0];
// console.log(pa.slice(0, 30));
var newPa = pa.slice(0, 29).concat('...');
rpa.textContent = newPa;
console.log(newPa)
<p>
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here
</p>

梦幻的心爱 2024-08-09 12:06:28

如果您想按 Limit(符号)截断,
但您不想剪切非长文本(例如帖子标题)的单词(保留最后一个单词完整):

trancWord(str, limit) {
    str = str.split(' ');
    let summ = 0
    for (let [index, value]  of str.entries()) {
        summ  += value.length
        if (summ > limit) {
            let cutTolimit = str.slice(0, index);
            return str.slice(0, index).join(' ') + ' ' + '...';
        }
    }
    return str.join(' ');
}

对于长字符串(帖子的一些长文本 - Vue-3 用作过滤器):

trancWord  (str, max){
        if (str.length <= max) { return str; }
        let subString = str.substr(0, max);
        return (str ? subString.substr(0, subString.lastIndexOf(' ')) : subString) + '...';
}

In case you want to truncate by Limit (symbols),
but you don't want to cut the words (leave the last word intact) for not LONG text (head of post for example):

trancWord(str, limit) {
    str = str.split(' ');
    let summ = 0
    for (let [index, value]  of str.entries()) {
        summ  += value.length
        if (summ > limit) {
            let cutTolimit = str.slice(0, index);
            return str.slice(0, index).join(' ') + ' ' + '...';
        }
    }
    return str.join(' ');
}

For long String (some long Text of Post - Vue-3 use as Filter):

trancWord  (str, max){
        if (str.length <= max) { return str; }
        let subString = str.substr(0, max);
        return (str ? subString.substr(0, subString.lastIndexOf(' ')) : subString) + '...';
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文