Fred Brack   Fred Brack  
Raleigh, NC
Picture of the Cape Hatteras lighthouse

An Introduction to JavaScript Strings
by Fred Brack
Updated

This is not a full tutorial on JavaScript strings but rather a brief introduction and reference to their basic features and how to manipulate them.  Want more detail?  Try Learn-JS, which helped me; and my favorite reference site is W3Schools.  I created this web page to help me document my understanding of JavaScript strings as I progress from novice to intermediate user ... and because I like to document stuff for others!  I hope you find it useful.

What Are Strings?

Strings are simply a series of characters defined between single or double quotes.

firstName = "Fred";
lastName  = 'Brack';

Although not an array, strings can be referenced character-by-character as if they were an array with each character an individual element of the array.  Remember:  In JavaScript, numbering starts at 0!  Thus:

firstChar = firstName[0]; // = 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!

String Properties

Well, basically there is only one:  length.

firstName = "Fred";
firstNameLth = firstName.length; \\ = 4

Regular Expressions

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

Caution:  my original example showed an asterisk instead of a dollar sign, and it was "Invalid JavaScript."  Why?  Because "/*" is the start of a (potentially multi-line) comment, and "*/" ends the comment.  To search for a comment (as the first or last item in a regular expression), you would have to write \*, using the escape character (\) in front of the asterisk.  Example:  /\*/.

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 

Need some more options?!  These are called metacharacters.  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!

/\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

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

With all of these options, you may be intimidated about creating a regular expression in your program.  Fortunately, JavaScript offers a way to test your regular expression:  the test method.  It's actually intended as a regular method for you to use in your programming, but you might want to use it to test a regular expression you build against a potential match to validate.  test returns true or false.

line = "Where's Fred?";
regexpr = /'/;      // look for an apostrophe - NOTE: NO QUOTES surround the slashes!
regexpr.test(line); // true
/'/.test(line);     // true // you can code the expression directly if you wish
/?/.test(line);     // INVALID JAVASCRIPT (because ? is a quantifier with nothing proceeding it!)
/\?/.test(line);    // true  ... because we used the ESCAPE CHARACTER (\) in front of ?
/\d/.test(line);    // false ... because there are no digits, and the \ is part of \d this time...
/se+/.test(line);   // false ... because no s is followed immediately by at least one e
/ed+/.test(line);   // true  ... because one e is followed immediately by at least one d
/\bf/.test(line);   // false ... because no word begins with lowercase f
/\bF/.test(line);   // true  ... because Fred begins with uppercase F
/\sF/.test(line);   // true  ... because a capital F appears after whitespace

String Methods

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;
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 (Only works with plain strings)
fullName.lastIndexOf("r");
  //LASTINDEXOF: find last pos of string r in Fred Brack ==> 6
fullName.search(regexpr);
  //SEARCH: find regexpr /r/ in Fred Brack ==> 1 (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/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.

You can find most of the above list of methods in my printable document:  JavaScript String Methods.

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

# # # # #

Fred