截断字符串直接JavaScript

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

这是我得到的:

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

解决方法:

使用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>"
上一篇:delete table 和 truncate table


下一篇:drop,delete与truncate的区别(到底在什么情况下使用什么呢?)