Javascript Strings

String objects are also somewhat different in how they work than other objects because in most cases the actual string methods can be applied to any text string regardless of whether it is defined using a new String() declaration or just specified within quotes.

Strings have one property and that is the length of the string.

There are a number of methods available which make it easier to extract specific information out of a string, update the content of a string or generally manipulate multiple strings in a variety of ways. Some of these methods allow you to use regular expressions which allow you to perform pattern matching with your text a very powerful way of manipulating text.

mystring.charAt(number)

extracts the single character at the specified position within the string while leaving the string intact

mystring.indexOf(substring)

finds the position where the specified substring starts within the string (or returns -1 if it can't be found)

mystring.lastIndexOf(substring)

finds the last occurrence of the substring within the string (which will be the same value as for indexOf unless there are at least two occurrences of the substring)

mystring.substring(start,end)
mystring.substr(start,length)

gets the specified part of the string

mystring.toLowerCase()

convert the string to lowercase

mystring.toUpperCase()

convert the string to uppercase

mystring.charCodeAt(number)

selects the single character at the specified position within the string and returns the ASCII code equivalent

mystring.concat(string2)

concatenates string2 onto the end of the string

String.fromCharCode(code)

converts the ASCII code back into the character that it represents, this is a static method not associated with any string

mystring.localeCompare(string2)

compares the string with string2 and returns -1, 0, or 1 depending on the sort sequence at the default locale

mystring.match(regexp)

searches for substrings within the string that match the regular expression and returns them in an array

mystring.replace(regexp,string2)

searches for substrings within the string that match the regular expression and replaces them with string2

mystring.search(regexp)

returns true if a substring within the string matches the regular expression

mystring.split(char)

splits the string at each occurrence of the specified character and puts them into an array (alternatively you can specify a regular expression instead of the char)

mystring.toLocaleLowerCase()

converts the string to lower case taking into account the default locale

mystring.toLocaleUpperCase()

converts the string to upper case taking into account the default locale

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate