JavaScript Tips

  |   Source

JavaScript String


There are two ways in JavaScript to get substring:

substr(StartIndex, Length):

Takes two parameter: StartIndex and Length of Substring (Optional)

substring(StartIndex, EndIndex)

Takes two parameter: StartIndex (inclusive) and EndIndex (exclusive). EndIndex is optional.

If "start" is greater than "end", this method will swap the two arguments, meaning str.substring(1,4) == str.substring(4,1).

If either "start" or "stop" is less than 0, it is treated as if it were 0.

Note: Both methods do not change the original string.

Special Cases

The two methods above have difference usage for following spceial cases:

Negative Value

substr() and substring() can both take negative value parameters as StartIndex, which means starting to count from end of string.

substr() can take Length parameter as negative number, but it will return a empty String.

substring() can take EndIndex as negative value, but this value will be ignored, and substring will start from position 0, has same length as Start Index.

If you only have one negative index, whole string will be returned, If you have a negative Start Index, nothing will be returned

So, if you want to take substring from the end of string, using substr(). Start from where your substring start, and length is what you need, or str.length - startIndex if you want rest of string.

Remember you substring has same sequence as original string. It's not reversed.

Two Way of Event Binding

$('#inputbox_id').bind('input', function(event){
//Second way: you may want keydown/keypress event also
$('#inputbox_id').on('keyup', function (event) {
*When you use copy and paster instead of key input, this way may cause double event trigger, so I prefer the way above

Common KeyCode

  • Delete:46

  • Backspace: 8

  • Enter: 13

  • Tab: 9

You can refer this cheatsheet for more keycode information.

Special Cases

From this stackflow post, IE doesn't fire keypress event for delete, end, enter, escape, function keys, home, insert, pageUp/Down and tab. So use keydown or keyup instead.

Comments powered by Disqus