Archive for August 3, 2007

JavaScript String Object lastIndexOf Method

Posted in JavaScript, programming on August 3, 2007 by Joey

The JavaScript string object contains an lastIndexOf method. It returns the index in the string of the last occurrence of a specified character. The index is numbered starting at 0. For example:

var strTest = 'joey javascript';
document.write(strTest.lastIndexOf('t'));

The index returned in the preceding example is 14, as there are 15 characters in the string, “t” is the last character and the index is numbered starting at 0.

The lastIndexOf method accepts an optional second argument – the position at which to begin the search.

var strTest = 'joey javascript';
document.write(strTest.lastIndexOf('j'));

In this example the index returned is 5. Since the search starts at the end of the string and works backwards it finds the last “j”, which is at position 5 in the string. If we tell the string to start looking backwards from the second position, however, the value returned will be the “j” at position 0, as follows:

var strTest = 'joey javascript';
document.write(strTest.lastIndexOf('j',2));

Related articles:
JavaScript String Object indexOf method

JavaScript Regular Expressions: Using Parentheses to Constrain Alternation

Posted in JavaScript, Regular Expressions on August 3, 2007 by Joey

In JavaScript regular expressions, parentheses can be used to constrain alternation. For example, if a string needs to be matched that begins with “hello” or “hi”, followed by a dash, one might try this regular expression:

document.write(/^hello|hi-/.test('hello'));//returns true

This will match a string that starts with “hello” or “hi” but will only require that the “hi” be followed by a dash. In order to constrain both “hello” and “hi” followed by a dash, parentheses need to be used:

document.write(/^(hello|hi)-/.test('hello'));//returns false

Related articles:
JavaScript Regular Expressions
JavaScript Regular Expression OR