我想使用直接的 JavaScript 截断动态加载的字符串。这是一个 url,所以没有空格,我显然不关心单词边界,只关心字符。
这是我得到的:
var pathname = document.referrer; //wont work if accessing file:// paths document.getElementById("foo").innerHTML = "<a href='" + pathname +"'>" + pathname +"</a>"
使用子字符串方法:
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>"