·  JavaScript – Syntax – Variables – String

 

- Info:

  - This tutorial shows how to work with strings in JavaScript.

 

- Create:

  - Strings are defined using either double or single qoutes.

  - If you use double qoutes you can use single qoute without escaping it and vice versa.      

    a = "I'm 30 years old.";   //No need to escape single qoute.

    a = "Word is \"jumbo\"";   //Escaping double qoutes.

    a = 'Word is "jumbo"';     //No need to escape double qoutes.

    a = 'I\'m 30 years old.'//Escaping single qoute.

    window.alert(a);

 

  - You can use following escape sequences to insert speacial characters:

   

Esc. Seq.

Escaped Character

 

\t

tab            

(HT, TAB)

 

\n

new line

(NL)

 

\r

return

(CR)

 

\f

form feed

(FF)

 

\b

backspace

(BS)

 

\a

alarm (bell)

(BEL)

 

\e

escape

(ESC)

 

\053

octal ascii char

print "\053";       #Displays '+'.

 

\x41

hex ascii char

print "\x41";       #Displays 'A'.

 

- Analyze:

  text   = "012345";

  index  = text.indexOf('3'    ); //First occurence of  '3'                 or -1.

  index  = text.indexOf('3' , 2); //First occurence of  '3' starting from 2 or -1.

  index  = text.indexOf("23"   ); //First occurence of "23"                 or -1.

  index  = text.indexOf("23", 2); //First occurence of "23" starting from 2 or -1.

  length = text.length;           //5. Returns number of characters in a string.    

 

- Get Substring:

  text    = "012345";

  sub     = text.substring (2);     //2345  Take substring from index 2 till the end.

  sub     = text.substring (2,4);   //23    Take substring from index 2 till excluding index 4.

 

- Modify:

  text = "aBCde-BC-bc";

  text = text.replace    ("BC","12"); //a12de-BC-bc. Substitute FIRST occurence of BC with 12.

  text = text.toUpperCase(text);      //ABCDE-BC-BC.

  text = text.toLowerCase(text);      //abcde-bc-bc.

 

- Connect:

  text1 = "Hello";

  text2 = "World";

    

  text  = text1 + " " + text2;

  text  = text1.concat(" ", text2);

    

  window.alert(text);