我希望从第二个位置给我4个字符。但不是。
<body id = "A">
<script>
var s = document.getElementById("A");
var d = "Hello, world";
s.innerHTML = d.substring(2,4);
</script>
它适用于:
d.substring(0,4);
答案 0 :(得分:6)
substring
的参数是开始和结束,而不是开始和结束。
string.substring(start,end)
Parameter Values
Parameter Description
start Required. The position where to start the extraction. First character is at index 0
end Optional. The position (up to, but not including) where to end the extraction. If omitted, it extracts the rest of the string
有一个加法函数substr
,其参数为start和length
string.substr(start,length)
Parameter Values
Parameter Description
start Required. The position where to start the extraction. First character is at index 0
length Optional. The number of characters to extract. If omitted, it extracts the rest of the string
您可以see more at "W3Schools" here ..您可能会发现这是您遇到的其他问题的有用参考。
答案 1 :(得分:2)
您需要substr()
var s = document.getElementById("A");
var d = "Hello, world";
s.innerHTML = d.trim().substr(2,4);
substr()
和substring()
是不同的方法!