Truncate a string straight JavaScript

2022-08-30 01:02:49

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>"

答案 1

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>"

答案 2

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;
  }
}