scorpio98
scorpio98

Reputation: 103

Why does this string property work?

function decinumber(y){
    var x = document.getElementById("areafield");
    if (y.match("del")){
        x.value = x.value.substr(0,(x.value.length-1)); return;
    }
}

I want to remove the last character from the x string. Now this code right here actually works, but my question is that why does this work? It sounds weird, but I don't know why. Since, in strings the first character is in position 0 not position 1, then the total length of that string minus 1 gives us the last character in that string not the one before the last one.

For example,consider this string-- "fireblow"

The length of this string is 8. "f" is at position 0, so 8-1 is 7, and that is the position of the last character "w" in that string not "o".

Upvotes: 0

Views: 66

Answers (3)

ZombieCode
ZombieCode

Reputation: 1661

The second parameter states how many characters you want to grab. Since you want to grab the entire string of X minus one character, you take the lenght of the string and minus 1 from it.

So now your substring states...

Grab 7 characters from this string starting at position 0.

To test this out and solidify your understanding try different combinations. Start at position 3, and take only two characters.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201437

This works because substr takes character 0 to the length of the string - 1 here

x.value = x.value.substr(0,(x.value.length-1));

See also, this JSFiddle -

var text = 'Help';
text = '<h1>' + text.substr(0,(text.length-1)) + 'lo</h1>';

and then text === "<h1>Hello</h1>"

Upvotes: 0

dave
dave

Reputation: 64657

substr(start_index, length);

If you do ("areafield").length you get 9. If you do ("a").length you get 1.

So, if we start with the character in the first position (index 0), and go 8 characters, we get

a r e a f i e l
1 2 3 4 5 6 7 8

Or with ("fireblow").length we get 8, so with .substr(0,(x.value.length-1))

f i r e b l o
1 2 3 4 5 6 7

Upvotes: 0

Related Questions