Javascript:切片和子字符串未按预期工作

标签 javascript string

我希望从第二个位置给我 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);

最佳答案

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 ..您可能会发现这对您遇到的其他问题很有用的引用。

关于Javascript:切片和子字符串未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23871029/

相关文章:

javascript - this.$root.$emit 在 Vue 中不起作用

c - C语言中使用字符串输入

c - 在使用 C++ 编译器编译代码时将 C 字符串文字传递给函数时遇到问题?

python - 如何在 python 中将 api 响应的一部分转换为完整的 json

java - 从用户获取日期并将其写入 URL

javascript - 将元素标题属性从同级克隆到 data-id

javascript - 如何嵌入带有侧边栏的 youtube 播放列表

javascript - 使用 onclick 在 href 上使用多个属性

javascript - 从 &lt;input type ='file'> 获取值返回空字符串

python - 如何在python中修剪字符串的n个字符?