Strings are simply a series of characters defined between single or double quotes.
firstName = "Fred"; lastName = 'Brack';
firstChar = firstName; // = F lastChar = firstName[firstName.length-1]; // = d
You can convert a number to a string via several methods:
n = 10; n$ = String(n); // = "10" n$ = n.toString() // = "10" n$ = ""+n // = "10" the geeks way of doing it!
Well, basically there is only one: length.
firstName = "Fred"; firstNameLth = firstName.length; \\ = 4
Before we show string methods, you need to make sure you understand what a regular expression is. A regular expression is a string of one or more characters delimited on both ends by a slash, the purpose of which is to define a search pattern for several functions. Note: You use the slashes instead of quotes. Here are several examples:
/a/ => search for the letter a /Fred/ => search for the word "Fred" /[xyx]/ => search for a match on x or y or z /[a-z]/ => search for any lowercase letter /[a-z]|[A-Z]|[0-9]|$/ => search for any lower or uppercase letter, a digit, or a dollar sign
Note that any search specified as above will stop on the first match, which is why we have options! Perhaps the most popular is g for global, meaning all of them, not just the first one. But we also have i for case-insensitive and m for multi-line matching. You specify the letter for one of more of these options immediately following the second slash.
/red/g => search for ALL occurrences of "red" /red/gi => search for ALL occurrences of "red" regardless of case
It is important to note that when you use the global option g with the match method (shown below in String Methods), which is very common, the result is an array, not a string. The array by itself is pretty useless (every element is the same -- the matching phrase), but the number of elements equals the number of hits; so testing the length of the array is meaningful. Examples:
text = "Fred waved a tattered red flag"; hit = text.search(/red/); // true hits = text.match(/red/g); // red,red,red (in an array) numberOfHits = hits.length; // 3 numberOfHits = text.match(/red/g).length; // 3
Need some more options?! These are called metacharacters or character classes and some of them are assertions. They all begin with a backslash, not to be confused with the backslash escape character, which makes the resulting expression look really odd and occasionally confusing, but that's how it goes! This is just a partial list. See the complete list of character classes.
/\d/ => find any digit /\bxxx/ => find a match at the beginning of word xxx /xxx\b/ => find a match at the end of word xxx /\s/ => find a whitespace character /\unnnn/ => find Unicode character nnnn /\n/ => find a linefeed (also known as CRLF on Windows computers) /\t/ => find a tab character
And then we have quantifiers, which define quantities. Note that x refers to the single character in front of the quantifier; thus /12?/ means 1 followed by zero or one 2s. Rather confusing!
/x+/ => find a string containing at least one x /x?/ => find a string containing zero or one x /x*/ => find a string containing zero or more x's
Here I present a list of string methods with brief explanations. To demonstrate these methods, we need to set up some variables on which to operate, so we will start with that.
fullName = "Fred Brack"; // remember, character position starts at 0 regexpr = /r/; // a “regular expression” denoted by the slashes
fullName.includes("r"); // return true or false //INCLUDES: is string r in Fred Brack? ==> true (Only works with plain strings) regexpr.test(fullName); // return true or false //TEST: is regexpr /r/ in Fred Brack? ==> true (Can take regular expressions as argument ==> more powerful) //NOTE: This could also have been written as "/r/.test(fullName)" fullName.indexOf("r"); //INDEXOF: find pos of string r in Fred Brack ==> 1 (-1 if not found; plain strings only) //NOTE: you can specify a second operand telling indexOf where to begin looking (default = 0) fullName.lastIndexOf("r"); //LASTINDEXOF: find last pos of string r in Fred Brack ==> 6 (-1 if not found; plain strings only) //NOTE: you can specify a second operand telling lastIndexOf where to begin looking (default = 0) fullName.search(regexpr); //SEARCH: find regexpr /r/ in Fred Brack and return its position ==> 1 (-1 if not found) // (Can take regular expressions as argument ==> more powerful) fullName.substr(0,4); //SUBSTR: extract the first 4 characters of Fred Brack ==> Fred fullName.substring(1,4); // meaning up to but not including 4 //SUBSTRING: extract characters 1 through 3 from Fred Brack ==> red fullName.toUpperCase(); //TOUPPERASE: convert Fred Brack to uppercase ==> FRED BRACK fullName.toLowerCase(); //TOLOWERCASE: convert Fred Brack to lowercase ==> fred brack fullName.startsWith("F"); // return true or false //STARTSWITH: does Fred Brack start with string 'F'? ==> true fullName.endsWith("ck"); // return true or false //ENDSWITH: does Fred Brack end with string 'ck'? ==> true fullName.charAt(1); //CHARAT: what character is at pos 1 in Fred Brack ==> r fullName.charCodeAt(1); //CHARCODEAT: what is the decimal character code at position 1 in Fred Brack ==> 114 fullName.match(/r/g); // use the global modifier to find ALL 'r's; return an array //MATCH: find pattern /r/g in Fred Brack ==> r,r //NOTE! This is useful because the LENGTH of the resulting array is the number of 'r's fullname.replace("r","x") // REPLACE: Replace the first occurrence of the first operand with the second ==> Fxed Brack // OR, especiall to use the global indicator ... fullName.replace(/r/g,"x"); //REPLACE: replace what's found with pattern /r/g in Fred Brack with x ==> Fxed Bxack fullName.slice(1,4); // from position 1 to 3 (not including position 4) //SLICE: extract (slice) positions 1 through 3 from Fred Brack ==> red fullName.split(" "); //SPLIT: split Fred Brack into parts separated by blanks, returning array ==> Fred,Brack //See the NOTE below to use this method to parse a string x = " "+fullName+" "; x.trim(); //TRIM: trim whitespace from beginning and end of ' Fred Brack ' ==> Fred Brack "*".repeat(10); //REPEAT: **********
NOTE: to parse a string into component variables, see Parsing Using an Array.
ONE MORE EXAMPLE: While technically not a String method, you could use the following number method to convert a number to a string rounding to a specified number of digits after the decimal point. The default is 0. This would be useful for printing a number to limit the width, for example.
var nbr = 1.23456; nbr.toFixed(); // = 1 nbr.toFixed(3); // = 1.235
You can obviously compare strings on your own using the regular comparison operators as appropriate (meaning special consideration for whether to use == or ===). You can also use the methods toLowerCase or toUppercase to help with your comparisons when they should be case-insensitive. Examples:
a == b; a === b; a.toLowercase < b.toLowerCase
Another option is the localeCompare method (locale, not local) which compares two strings and returns one of three possible return codes:
one = "Fred"; two = "Fred Brack"; alert(one.localeCompare(two)); // = -1, or at least something <0
You should note the implied warning to check for negative or positive values, not -1 or +1, which can vary by browser. Also note that there are two additional optional operands available:
# # # # #