1/21/2014

String | JavaScript Tutorial
Log in

JavaScript Tutorial
Home » Tutorial » JavaScript: from the Ground to Closures » Mastering data types
‹ Functions: declarations and expressions Number, Math › Tutorial

JavaScript: from the Ground to Closures
JavaScript: from the Ground to Closures Javascript and related technologies First Steps Functions: declarations and expressions Mastering data types
Mastering data types String Number, Math Objects Array Conversion, toString and valueOf

String
Ilya Kantor

1. String creation 1. Special characters 2. Escaping, special chars 2. Methods and properties 1. Length 2. Accessing characters 3. Manipulating strings 4. Lowercasing / Uppercasing 5. Finding a substring 6. Extracting a substring: s u b s t r ,s u b s t r i n g ,s l i c e . 3. Comparison 1. Strings vs Numbers 4. Summary The String is by far one of the most used type in JavaScript.

Like

3

Four scents of "this" Type detection Function arguments Static variables and methods Scopes and Closures Decorators

There are programming languages that differ “chars” from “strings”. But in JavaScript, there are only strings, no chars. That really makes life simpler. Another feature is that internally all strings are unicode, no matter which encoding is used.

Document and Events Object Oriented Programming Timing Frames and windows Regular expressions in JavaScript Advanced and Extra stuff

String creation
String objects are usually created using string literals: v a rt e x t=" m yv a l u e " ; v a ra n o t h e r T e x t=' a n o t h e rs t r i n g ' ; v a rs t r=" 0 1 2 3 4 5 " ; There is no difference between single and double quote in JavaScript. String literals may contain special characters denoted by escape-sequences, a newline symbol and others.

Donate Donate to this project

Special characters
Here is a list of special characters and sequences: Character \b \f \n \r \t \uNNNN Description Backspace Form feed New line Carriage return Tab The Unicode character which code is given by the four hexadecimal digits NNNN. For example, \u00A9 is the Unicode sequence for the copyright symbol.

Note that strings in JavaScript are Unicode internally. The newline symbol is by far the most popular:
Run!

1 v a rm u l t i L i n e="f i r s t\ ns e c o n d\ nt h i r dl i n e" 2 a l e r t ( m u l t i L i n e )/ /a l e r t s3l i n e s

Escaping, special chars
An escaping is prepending a character by backslash ‘'. First, if single quotes appear inside a single-quoted string, they need to be escaped : v a rs t r=' I \ ' mt h eV a l r u s ' In this particular case the double-quoted string could work also: v a rs t r=" I ' mt h eV a l r u s " / /n on e e de s c a p i n g .

http://javascript.info/tutorial/string

1/5

use c h a r A tcall. t o U p p e r C a s e ( )) The following code gets the first char and lowercases it. a l e r t (" H e y h o ! " . Run! 1 v a rs t r=" M y \ n "/ /3c h a r a c t e r s . c h a r A t ( 2 )+s t r . c h a r A t ( 3 )+s t r . so c h a r A tactually returns a substring containing exactly one symbol. Let’s discuss the most important ones first. like in the example below: Run! 1 v a rs t r=" s t r i n g " 2 3 s t r=s t r . First character starts at 0 : Run! 1 v a rs t r=" c a t t y " 2 a l e r t (s t r . Use c h a r A t .calls get characters on given positions and operator " + " performs concatination (joining) of them. Escaping is required for double quotes inside a double-quoted string: v a rs t r="d o u b l e\ "q u o t e" Backslash symbol ‘' has to be escaped always: Run! 1 v a rs t r="' \ \ '" 2 3 a l e r t ( s t r )/ /' \ ' Methods and properties There are many properties in JavaScript strings. . . Lowercasing / Uppercasing Methods t o L o w e r C a s e ( )and t o U p p e r C a s e ( )change the case of a whole string: Run! 1 a l e r t (" H e y h o ! " . t o L o w e r C a s e ( )) Create a function u c F i r s t ( s t r )which returns s t rwith uppercased first character: u c F i r s t ( " j o h n " )= =" J o h n " Note.1/21/2014 String | JavaScript Tutorial The same applies to double quotes. c h a r A t ( 0 )) / /" c " There is no “character” type in JavaScript.T h et h i r ds y m b o li sn e w l i n e 2 3 a l e r t ( s t r . c h a r A t ( 5 ) 4 5 a l e r t ( s t r )/ /r i n g In this example s t r .c h a r A t ( 3 ) . You can read a character.info/tutorial/string 2/5 . Length Every string has a length (a number of unicode symbols). In recent browsers (excluding IE<8) you can also use index to access the character: Run! 1 v a rs t r=" I ' mt h em o d e r nb r o w s e r ! " 2 a l e r t ( s t r [ 0 ] ) / /" I " Manipulating strings A string cannot be changed in JavaScript. c h a r A t ( 0 ) . c h a r A t ( 2 ) . there is no single method in JavaScript that can do so. but you can’t replace it. l e n g t h ) / /3 Accessing characters To access a single character. The usual workaround is to change a string variable: create a new string and reassign it instead of the old one. c h a r A t ( 4 )+s t r . Open solution http://javascript.

i n d e x O f ( " W i d g e t " ))/ /0 a l e r t (s t r . but not including position e n d . The function should be case-insensitive: c h e c k S p a m ( ' b u yV i A g R An o w ' )= =t r u e c h e c k S p a m ( ' f r e ex x x x x ' )= =t r u e c h e c k S p a m ( " i n n o c e n tr a b b i t " )= =f a l s e Open solution Extracting a substring: s u b s t r . i n d e x O f ( " i d " ))/ /1 a l e r t (s t r . there are 3 (!) methods to extract a portion of a substring. In the article Operators. Just remember: ' ~reads as “not minus one”.s u b s t r i n g . s u b s t r i n g ( 2 ) )/ /r i n g i f y s u b s t r ( s t a r t[ .info/tutorial/string 3/5 . from the end of the string. because ~ 1= =0 : Run! 1 a l e r t (~ 1)/ /0 The check match becomes ~ i n d e x O f : Run! 1 v a rs t r=" W i d g e t " 2 i f (~ s t r . there was a bitwise NOT ‘~’ operator: ~ nis same as ( n + 1 ) .l e n g t h ] ) The first argument is same as in s u b s t r i n g .1/21/2014 String | JavaScript Tutorial Finding a substring To find a substring. So. and " i f ~ i n d e x O f "reads as " i ff o u n d " . The count starts from 0. i n d e x O f ( " g e t " )){ 3 a l e r t ( ' m a t c h ! ' ) 4 } Generally.s e a r c hs t a r t sf r o mc h a r2 There is also a similar method lastIndexOf which searches backwards. abusing language features in a non-obvious way is a bad thing. everything’s all right. because lowers readability. i n d e x O f ( " L a l a l a " ))/ /1 An optional second argument allows to search from an index.e n d )extracts a substring from s t a r tto. For example. i n d e x O f ( " i d " . It returns the position of a first occurence of a substring or -1 if nothing found: Run! 1 2 3 4 5 v a rs t r=" W i d g e tw i t hi d " a l e r t (s t r . Run! 1 v a rs t r=" s t r i n g i f y " 2 a l e r t ( s t r . Create a function c h e c k S p a m ( s t r )which returns t r u eif s t rcontains ‘viagra’ or ‘XXX’. it goes till the end of string: Run! 1 v a rs t r=" s t r i n g i f y " 2 a l e r t ( s t r . but second argument is “how many characters to extract” http://javascript.2 ))/ /1 2 . s u b s t r i n g ( s t a r t[ .e n d ] ) Method s u b s t r i n g ( s t a r t . s u b s t r i n g ( 0 . there exists an indexOf method. let’s find one more: Run! 1 v a rs t r=" W i d g e tw i t hi d " 2 3 a l e r t (s t r . but with minor differences. But here. the first occurence of " i d "is at index 1. In JavaScript. This feature is used to check for -1.s l i c e . 1 ) )/ /" s " If e n dis omited.

. c h a r A t ( 0 )with b = s 2 . The returned value is a (possibly) corrected string For example: t r u n c a t e ( " a n dh e r ei sw h a tIw a n tt os a yo nt h a tm a t t e r : " . s l i c e ( s t a r t[ . Run! String | JavaScript Tutorial 1 v a rs t r=" s t r i n g i f y " 2 s t r=s t r . if s t a r t>e n d .e n d ) Negative values become zero. That’s same as s u b s t r i n g . 4 )/ /r i n g 3 a l e r t ( s t r ) Again. the idea is to get a substring between two indices.4 )=" t e s t " That arguments swapping is kind of counter-intuitive. But guess.1 )) / /" t e s t " 2 / /1b e c o m e s0>g i v e su ss u b s t r i n g ( 4 . Too large value becomes string length: Run! 1 a l e r t (" t e s t m e " . 'to make the length equal to m a x l e n g t h . .info/tutorial/string 4/5 . s l i c e ( 1 .f r o m2 n dt o2 n df r o mt a i l . s l i c e Negative values mean to go backwards from the tail: Run! 1 a l e r t (" t e s t m e " . but not including position e n d . The difference between s u b s t r i n gand s l i c eis how they treat negative and overflow values: s u b s t r i n g ( s t a r t . Compare first chars: a = s 1 . s u b s t r i n g ( 4 .2b e c o m e s0 Also. alternatively.l e n g t h )with non-negative s t a r t(negative doesn’t work in IE). The method of choice is s l i c e ( s t a r t . it cuts s t rand appends it with ' . s l i c e ( 2 )) / /" m e " . .1/21/2014 instead of ending position. the arguments are swapped: Run! 1 a l e r t (" t e s t m e " . If they are equal then continue. Conclusion.1 )) / /" e s t m " . If the length of s t ris more than m a x l e n g t hchars. .2 0 ) )=" h it oa l l ! " This function is useful not just for a task.m a x l e n g t h )that check string s t rlength. That’s much more convenient than s u b s t r i n g . the omitted second parameter means go till the end of string. Open solution Comparison Strings are compared lexicographicaly. in truncating user-given subjects etc. c h a r A t ( 0 ) .e n d ) . Write a function t r u n c a t e ( s t r . s u b s t r i n g ( 2 )) / /" t e s t m e " . Negative indexes are also supported in s u b s t rby all browsers except IE.f r o mp o s i t i o nl a s t 2t oe n d Run! 1 a l e r t (" t e s t m e " .e n d ] ) Returns a portion of the string from position s t a r tto. else return > or < http://javascript.2 0 ) )=" a n d h e r ei sw h a t. but for real-life. s u b s t r ( 2 . For two strings inequality s 1>s 2is checked using simple algorithm: 1. " t r u n c a t e ( " h it oa l l ! " .0 ) 3 / /4>0s oa r g u m e n t sa r es w a p p e d>g i v e su ss u b s t r i n g ( 0 . Or. s u b s t r ( s t a r t .

that’s all we need in most of cases. 2011. then both operands become numbers. that’s important in JavaScript also. / /f a l s e 2 a l e r t ( " 2 ">" 1 4 " ) .b e c a u s ea na b s e n c eo fac h a ra l w a y sl o s e si nc o m p a r i s o n Check it out: a l e r t ( " a ">" Z " )/ /t r u e . "JavaScript™ is a registered trademark of Oracle corp. http://javascript. How to extract a portion of string.1/21/2014 2. Compare second character./ /f a l s e That’s because if any of the operands is not string. with special symbols and quoting.b e c a u s e" 2 ">" 1 "( f i r s tc h a rm a t t e r s ) But note: Run! 1 a l e r t ( 2>" 1 4 " ) . This site is not affiliated with Oracle corp. " Z ">" A "/ /t r u e " B o b ">" B a r "/ /t r u e . Number. etc String | JavaScript Tutorial The standard defines that more precisely.info/tutorial/string 5/5 . Math › The content of this site is available under the terms of CC BY-NC-SA. © Ilya Kantor. you can browse Mozilla manual ‹ Functions: declarations and expressions . How to strings are compared. This order we can see in a dictionary or a phonebook.b e c a u s eo>a " a a ">" a " / /t r u e . In addition to concatenation which is done by “+” operator. although the point is clear (I hope): characters are compared one by one. To learn about other methods of String. and the comparison becomes correct.c a u s el o w e r c a s e dl e t t e r sg oh i g h e ri nb r o w s e rc h a r a c t e r s l i s t Strings vs Numbers Note the difference in behavior between strings and numbers in comparisons: Run! 1 a l e r t ( 2>1 4 ) . Summary Now you know: How to write a string. Later we’ll discuss regular expression./ /t r u e .