Strings

  • Series of characters, strung together
  • Quotes are used to encapsulate a string
  • Can be single or double quotes
    • var myString = "This is a string in double quotes" ;
    • var myString = 'This is a string in single quotes' ;
  • Cannot be mixed within the same statement
    • var myString = "This will not work as expected since it has mixed quotes' ;
  • If one or the other is required within a string it can be
    • escaped by using the backslash \
      • var myString = 'Escaping it\'s single quote with a backslash' ;
    • Use the other quotes
      • var myString = "Using a single inside it's double quotes" ;

 

Strings can also be treated as objects (with properties and methods) that have information we can access. For instance to find the length of a string we could use the .length property:

var myString = "Here's a bunch of uninteresting text" ;

document.write(myString.length); //returns 36, including all characters and spaces

document.write(myString.toUpperCase()); //returns: HERE'S A BUNCH OF UNINTERESTING TEXT

 

.toLowerCase()

.split(" ") //passing in a space, to split string apart (in this case using a space) into an array

.indexof("bunch") //returns the index position of where the passed in term starts = 9

*note: if the term is not found it will return -1

.lastIndexOf("te") //returns the last index position of where the passed in term is found = 32

 

 

Slice

var myString = "Another mundane simple line of text!" ;

var mySlice = myString.slice(8, 15) ;//starting position from 0, up to (but not including) ending position = mundane

 

.substring(start, end) //same as above

.substr(start, length) //uses length as the number of characters to return

 

 

Comparison

Case sensitive

 

var string1 = "animal" ;

var string2 = "banana" ;

if (string1 < string2 ) {  //true

var string1 = "animal" ;

var string2 = "Banana" ;

if (string1 < string2 ) {  //false

 

Upper case letters are considered less than lowercase letters.

 

https://developer.mozilla.org/en/JavaScript/Reference

Leave a Reply