Thursday, 20 August 2015

In Detail: Strings In JavaScript

Strings In JavaScript:

    Just like in Java, Strings are immutable in JavaScript also. They are sequence of JavaScript characters. Each character in JavaScript is represented by 16 bit UTF-16 code unit.

How to create Strings in JavaScript:

The different ways in which you can make strings in JavaScript are as follows.
1.    Using String Literals.
2.    Using String() function.
3.    Using String() constructor.

Using String Literals:

    You can use either single (‘) or double (“) quotes to create strings. You just need to enclose your sequence of characters between single or double quotes. For ex:
 var a = 'abc'; var b = "abc"; 
Both the statements create String values. Therefore you are free to use any kind of quote.

Using String () function:

    The String() function expects a value as parameter. If the value is not a character sequence, it converts to String. For ex:
var str = String("abc"); // value of str is "abc".
You can use this function for converting other value types to String type. The conversion happens like below.
Value type Result
undefined 'undefined'
null 'null'
A Boolean false – 'false', true – 'true'
A number 3.41 – '3.41'
A String no conversion happens, value is already string
An object a call to ToPrimitive(value, String) happens and converts the resulting primitive.
Using String() constructor:

    The function String() as a constructor, it creates a new instance of String. The type of newly created String is Object. Let’s see an example
var str = new String(“abc”); // “abc”.
typeof str; // ‘object’
You can also construct String from character code units, using String.fromCharCode() function just like below.
var str = String.fromCharCode(97,98,99); // gives “abc”.
Escaping in String literals:
    In case, If your string contains any of special characters such as (\t,\b,\r,...), JavaScript interprets and replaces with their respective values. So if you don’t want JavaScript to interpret, use backslash before any such special characters. Below are some examples.

Use (\) in cases where, String spreads to multiple lines for ex:
var str = "abc \

cde \

def"; is valid String literal, whereas 

var str = “abc


def”; is not valid, JS throws syntax error. 

To escape control characters:
    Control characters such as \b (back space), \f (form feed),\n(new line), \r (carriage return), \t (horizontal tab), \v (vertical tab), have special meaning. for ex:
var a = “abc\tdef”; // "abc    def"
so if you want to escape control characters, use another back slash before control character. So
var a = ‘abc\\tdef’; // "abc\tdef"

NUL character: represented by \0;
Hexadecimal escape sequences: Hex decimal sequences specify a character via an ASCII code. They starts with \x
For ex:
‘\x4D’ represented ASCII character M.
Unicode escape sequences: Unicode specifies a UTF-16 code unit. They starts with \u. for example, the equivalent Unicode for character M is
‘\u004D’; // M

‘\u03C0’;// "π"

var c = ‘\\u004D’; // value of c is \u004D, not M.

Accessing Individual characters of String:
You can access characters of a JavaScript in 2 ways.
Using charAt() : you need to pass the position of a character to this method. Position starts from 0.
‘abc’.charAt(1); // gives b
Using square brackets ([]): instead of charAt() method you can use [] to access character at a given position. For example.
‘abc’[1] ;// gives b
Note that JavaScript doesn’t have a special data type for characters. Both the above operations return strings only.

Comparing Strings:
You can compare strings in two ways. First, you can use the comparison operators such as <, > , ===, <=, >=. For ex:
‘B’ > ‘A’ // true, it compares ASCII value of both strings.

‘B’ > ‘a’ // false 
Another way is using localeCompare(other) function of String object,
It returns 0, if two strings are same,
greater than 0: if receiver is larger than the argument,
less than 0: if the receiver is smaller than the argument. For eg:
‘B’.localeCompare(‘A’); // 1, means ‘B’ is greater than A. 
Concatenating Strings:
You can use + operator for concatenating Strings. For ex:
Var str = “”;

str += “abc”;

str += “ cde”;

str += “ def”;

console.log(str); // prints abc cde def

Other properties and methods of String Instance:
Gives number of JavaScript characters in the give String.
‘abc’.length; // 3
Extract Substrings:
charAt(pos): returns a string with the character at position pos. for ex:
‘abc’.charAt(1); // ‘b’

charCodeAt(pos): works similar to charAt(pos), but returns the code (a 16bit unsigned integer) of the JavaScript character at position pos.
‘abc’.chartCodeAt(1); // 98
slice(start, end):
returns the substring starting at position start up to and excluding position end. If you don’t pass end, then it considers length of string as end. For ex:
‘abc’.slice(2); // ‘c’.

‘abc’.slice(1, 2); // ‘b’

If you pass, negative parameters, then the length of the string is added to them. For ex:
‘abc’.slice(-2); // ‘bc’. Is equivalent to 

‘abc’.slice(1); // ‘bc’
Split(separator?, limit?):
Splits the string based on the separator and returns them in an array. Here separator is either a string or regular expression. If not passed, the complete string is returned, wrapped in an array.limit if given, the returned array contains at most limit elements.
For ex:
‘a, b,c, d’.split(‘,’); // [‘a’, ‘ b’,’c’,’ d’]

‘a, b,c, d’.split(/,/); // [‘a’, ‘ b’,’c’,’ d’]

‘a, b,c, d’.split(/, */); // [‘a’,’b’,’c’,’d’]. Here /, */ means- comma separated by zero or more spaces.

‘a, b,c, d’.split(/, */,2);// [‘a’,’b’] – with limit applied on split method

Use empty string as separator to produce an array with the characters of string.
‘abc’.split(‘’); // [‘a’,’b’,’c’]

Removes all white spaces from the beginning and the ending of the string.
‘    abc    ‘.trim();// ‘abc’

Concatenates receiver and str1, str2, etc:
‘abc’.concat(‘ ‘,’cde’,’ def’); // abc cde def
creates a new string with all of the original string’s characters converted to lowercase:
‘ABC’.toLowerCase(); // ‘abc’
creates a new String with all of the original string’s characters converted to upper case.
‘abc’.toUpperCase(); // ABC
Searches for searchString starting at given position. If position is not specified, 0 is considered as position. Returns position where searchString has been found or -1 if not found.

‘abcabc’.indexOf(‘b’,2); // 4

lastIndexOf(searchString, position):
searches for searchString, starting at position (default is the end), backward. It returns the position where searchString has been found or -1 if not found. For ex:
‘abcabc’.lastIndexOf(‘b’); // 4

‘abcabc’.lastIndexOf(‘b’,3);// 1


Post a Comment

Note: only a member of this blog may post a comment.