Reputation: 193
I expect to give me 4 characters from second position. but doesn't.
<body id = "A">
<script>
var s = document.getElementById("A");
var d = "Hello, world";
s.innerHTML = d.substring(2,4);
</script>
It work when:
d.substring(0,4);
Upvotes: 0
Views: 4434
Reputation: 4843
The arguments for substring
are start and end, not start and length.
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
There is an addition function substr
that has arguments of start and 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
You can see more at "W3Schools" here .. you may find this a useful reference for other issues you encounter.
Upvotes: 8
Reputation: 17366
You need substr()
var s = document.getElementById("A");
var d = "Hello, world";
s.innerHTML = d.trim().substr(2,4);
substr()
and substring()
are different methods!
Upvotes: 3