我想用JavaScript截断一个动态加载的字符串。这是一个url,所以没有空格,我显然不关心单词的边界,只关心字符。
以下是我得到的答案:
var pathname = document.referrer; //wont work if accessing file:// paths
document.getElementById("foo").innerHTML = "<a href='" + pathname +"'>" + pathname +"</a>"
我想用JavaScript截断一个动态加载的字符串。这是一个url,所以没有空格,我显然不关心单词的边界,只关心字符。
以下是我得到的答案:
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>"
其他回答
要将字符串截断为特定长度,请在JavaScript中使用以下单线性箭头函数:
const truncate = (str, len) => str.slice?.(0, len);
console.log(truncate("Hello, World!", 5));
// Expected Output: Hello
上面的函数使用string .prototype.slice方法,该方法获取字符串的一个块,并将其作为一个新字符串返回,而不改变原始字符串。
是的,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;
};
使用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>"
一行ES6解决方案
如果字符串长度超过给定长度,它还会添加一个结束字符串,而不仅仅是截断字符串。
const limit = (string, length, end = "...") => {
return string.length < length ? string : string.substring(0, length) + end
}
limit('Hello world', 5) // Hello...
var str = "Anything you type in.";
str.substring(0, 5) + "" //you can type any amount of length you want