JavaScript Reference: Strings


Creating Strings

Strings can be any combination of letters, numbers, and special characters, surrounded by single or double quotation marks. You can give your string a variable name to refer to it later.
// Two strings:
var firstString = 'Hello world'
var secondString = "nice to meet you"

Anything can be converted to a string using the String method:
var newString = String( 6+5+"hello" )
// newString is now the string '11hello'

Concatenation

Two or more strings can be joined using the + symbol. Strings can be concatenated using variables. If a number or mathematical expression is "added" to a string, it will be converted to a string (the expression cannot be surrounded by quotation marks, or it will be interpreted literally). Whitespace is not ignored, so be sure to include spaces where needed.
var firstString = 'Hello world'
var secondString = "nice to meet you"
var message = firstString + " it is " + secondString
console.log(message)
would result in
Hello world it is nice to meet you

var x = 3, y = 5
var sumString = "The sum of " + x + " and " + y + " is " + (x+y)
console.log(sumString)
would result in
The sum of 3 and 5 is 8

Special Characters

The backslash \ that comes before a character in a string means that the string should not include the character, but instead interpret it according to the chart below.
CharacterInterpretationExampleExample Returns
\0Null character, escape in numeric string"hello\0goodbye"
"85\04"
hellogoodbye
85
\'Single quotation mark"hello\'goodbye"hello'goodbye
\"Double quotation mark"hello\"goodbye"hello"goodbye
\\Backslash"hello\\goodbye"hello\goodbye
\nNew line"hello\ngoodbye"hello
goodbye
\xCharacter with hex value HH"\x23"#
\xHHCharacter with hex value HH"\x23"#
\uXXXXCharacter with hex value XXXX"\u00E9"é

String Properties

length

  • Use: Find the length of a string (the number of characters)
  • Format: stringName.length
  • Example:
    var aString = "Hello world"
    aString.length 	// returns 11 

String Methods

A summary of available methods for working with strings:

fromCharCode

  • Use: Convert a list of Unicode values to a string
  • Format: String.fromCharCode( unicode1, unicode2, ... )
  • Example:
    var hiddenMessage = String.fromCharCode(72,69,76,76,79,32,87,79,82,76,68)
    console.log( hiddenMessage ) 
    would result in
    'HELLO WORLD'

anchor

  • Use: Create and display HTML anchors
  • Format: stringName.anchor( anchorString )
  • Example:
    var anchorText = "Section One"
    document.body.innerHTML = anchorText.anchor('section_one_anchor')
    would output the following HTML:
    <a name = "section_one_anchor">Section One</a>

charAt

  • Use: Get the character at a particular position in a string
  • Format: stringName.charAt( index_value )
  • Example:
    var lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." 
    var firstLetter = lorem.charAt(0)
    var tenthLetter = lorem.charAt(9)
    var lastLetter = lorem.charAt(lorem.length - 1)
    console.log( firstLetter, tenthLetter, lastLetter )
    would result in
    L u .

charCodeAt

  • Use: Get the character's Unicode value at a particular position in a string
  • Format: stringName.charCodeAt( index_value )
  • Example:
    var lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." 
    var firstLetter = lorem.charCodeAt(0)
    var tenthLetter = lorem.charCodeAt(9)
    var lastLetter = lorem.charCodeAt(lorem.length - 1)
    console.log( firstLetter, tenthLetter, lastLetter )
    would result in
    76 117 46

indexOf

  • Use: Returns index of first instance of a character (or string) within a string
  • Format: stringName.indexOf( 'substring' )
  • Example:
    var lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." 
    var firstA = lorem.indexOf('a')
    var firstIp = lorem.indexOf('ip')
    console.log( firstA, firstIp )
    would result in
    22 6

lastIndexOf

  • Use: Returns index of last instance of a character (or string) within a string
  • Format: stringName.lastIndexOf( 'substring' )
  • Example:
    var lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." 
    var lastA = lorem.lastIndexOf('a')
    var lastIp = lorem.lastIndexOf('ip')
    console.log( lastA, lastIp )
    would result in
    122 42

link

  • Use: Create and display an HTML link
  • Format: stringName.link( url )
  • Example:
    var linkText = 'Mercyhurst Math Site'
    var MMurl = 'http://math.mercyhurst.edu'
    document.write( 'Get more information at the ' + linkText.link(MMurl)
    would result in the following text, with link, in the HTML document:
    Get more information at the Mercyhurst Math Site

slice

  • Use: Create a new string by extracting a section of an existing string between two indices
  • Format: newString = oldString.slice( startIndex, endIndex )
  • Example:
    var lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." 
    var loremSubstring = lorem.slice( 6, 17 )
    console.log( loremSubstring )
    would result in
    ipsum dolor

substr

  • Use: Create a new string by extracting a section of a particular length from an existing string
  • Format: newString = oldString.substr( startIndex, lengthOfSubstring )
  • Example:
    var lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." 
    var loremSubstring = lorem.substr( 6, 11 )
    console.log( loremSubstring )
    would result in
    ipsum dolor

split

  • Use: Separate a string into array elements
  • Format: arrayName = stringName.split( separator )
  • Example:
    var dogString = "labrador,boxer,papillon,chow chow,bulldog"
    var dogArray = dogString.split(",")
    console.log(dogArray)
    would result in
    [ 'labrador', 'boxer', 'papillon', 'chow chow', 'bulldog' ]

toLowerCase

  • Use: Convert letters in a string to lower case
  • Format: stringName.toLowerCase( )
  • Example:
    var myString = "Hello WORLD"
    console.log( myString.toLowerCase() )
    would result in
    hello world

toUpperCase

  • Use: Convert letters in a string to upper case
  • Format: stringName.toUpperCase( )
  • Example:
    var myString = "Hello WORLD"
    console.log( myString.toUpperCase() )
    would result in
    HELLO WORLD

trim

  • Use: Remove whitespace from both ends of a string
  • Format: stringName.trim( )
  • Example:
    var myString = "    Hello WORLD  "
    console.log( myString.toUpperCase() )
    would result in
    Hello WORLD

Modifying Strings with Regular Expressions

Be sure to review the expressions section for an explanation of regular expressions and pattern notation.

match

  • Use: Returns array with pattern matches or null if match is not found
  • Format: stringName.match( pattern )
  • Example:
    var lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." 
    var pattern1 = /(in)/g		// find all occurrences of 'in' 
    var result1 = lorem.match(pattern1)
    // result1 = [ 'in', 'in' ]
    var pattern2 = /l\w+/gi		// find all words starting with l, regardless of case	
    var result2 = lorem.match(pattern2)
    // result2 = [ 'Lorem', 'lor', 'lit', 'labore', 'lore', 'liqua' ]

search

  • Use: Returns index of first occurrence of pattern in a string
  • Format: stringName.search( pattern, 'replacement string' )
  • Notes: Use $n to refer to the nth substring
  • Example:
    var sampleString = "Hello world!" 
    var pattern = /l/		 
    var result = sampleString.search(pattern)	// find index of first 'l' in string
    result = 2

replace

  • Use: Replace a substring by pattern
  • Format: stringName.replace( pattern, 'replacement string' )
  • Notes: Use $n to refer to the nth substring
  • Example:
    var sampleString = "Hello world!" 
    var pattern = /(hello)/i		// find first occurrence of hello, regardless of case 
    var result = sampleString.replace(pattern, 'Goodbye')
    // result = 'Goodbye world!'
    
    var pattern = /l/g				// find all occurrences of 'l' 
    var result = sampleString.replace(pattern, 'k')
    // result = 'Hekko workd!'
    
    var nameString = "John Smith"
    var pattern = /(\w+)\s(\w+)/	// look for pattern word-space-word
    var newNameString = nameString.replace(pattern, '$2, $1')	// second word-comma-first word
    // newNameString = 'Smith, John'