Search

10/04/2007

Javascript: substring, substr

Tsung's Blog | JavaScript: substr() 負數的算法 IE, Firefox 不同

語法 string.substring(from, to)
  • from: A nonnegative integer that specifies the position within string of the first character of the desired substring.
  • the length of the returned substring is always equal to to-from.
  • String.slice( ) and the nonstandard String.substr( ) can also extract substrings from a string. Unlike those methods, String.substring( ) does not accept negative arguments.

語法 string.substr(start, length)
  • from: If this argument is negative, it specifies a position measured from the end of the string: -1 specifies the last character, -2 specifies the second-to-last character, and so on.
  • Negative values for start do not work in IE 4 (this is fixed in later versions of IE). Instead of specifying a character position measured from the end of the string, they specify character position 0.




https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Slice

語法 array.slice: The slice() method selects a part of an array, and returns the new array. Note: The original array will not be changed.
* For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

* For strings and numbers (not String and Number objects), slice copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.


javascript:alert('abcde'.slice(-3,-2)); // c


update: 測試的結果是IE 6的substr第一個參數不可為負數, 所以如果要cross browser的話, 不管是substring, substr 第一個參數皆不可為負

update2: ie6的slice 用在 string 上兩個參數都可以為負數

沒有留言: