Sujay Kundu

Full Stack Web Developer, Blockchain, Security

Posted by : at

Category : programming   javascript

Javascript ES5 - String Methods

Finding a String Length

var str = 'This is a string';
var len = str.length;

console.log(len);

// return 16

Finding a String in a String

indexOf(), lastindexOf()

indexOf()

The indexOf() method is used to return the index of (the position of) the first occurrence of a specified text in the string:

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");

console.log(pos);
// 7 

lastIndexOf()

The lastIndexOf() method is used to return the index of ( the position of) the last occurence of a specified text in the string :

Note:

Syntax : string.lastIndexOf(searchvalue, start)

searchvalue : The string to search for:

start: The position where to start the search ( searching backwards).

This method returns -1 if the value to search for never occurs.

Also lastIndexOf() method is case sensitive !

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");

console.log(pos);
// 21

Search a string in a string

search()

The search() method searches a string for a specified value and returns the position of the match:

var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");

console.log(pos);
// 7

The two methods, indexOf() and search(), are equal?

They accept the same arguments (parameters), and return the same value?

The two methods are NOT equal. These are the differences:

The search() method cannot take a second start position argument.
The indexOf() method cannot take powerful search values (regular expressions).

Extracting String Parts

slice(), substring() , substr()

slice()

slice() extracts a part of a string and returns the extracted part in a new string.

Syntax : slice(start, end)


var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);

console.log(res);
// Banana

If a parameter is negative, the position is counted from the end of the string.

var str = "Apple, Banana, Kiwi";
var res = str.slice(-12, -6);
console.log(res);

// Banana

substring()

substring() is similar to slice(). The difference only being that it cannot accept negative indexes.


var str = "Apple, Banana, Kiwi";
var res = str.substring(7,13);
console.log(res);

// Banana

substr()

substr() is similar to slice(). The difference only being that the second parameter specifies the length of the extracted part.


var str = "Apple, Banana, Kiwi";
var res = str.substr(7,6);

console.log(res);
// Banana 

Replacing String Content

replace()

The replace() method replaces a specified value with another value in a string:


str = "Please visit Thailand! ";
var n = str.replace("Thailand", "Bangalore");

console.log(n);

// Please visit Bangalore!

To replace case insensitive, we use a regular expression with an /i flag (insensitive):

str = "Please visit Thailand!";
var n = str.replace(/THAILAND/i, "Bangalore");
console.log(n);

// Please visit Bangalore!

To replace all matches, we use a regular expression with a /g flag (global match):

str = "Please visit Thailand and Thailand will welcome you !";
var n = str.replace(/THAILAND/g, "Bangalore");
console.log(n);

// Please visit Bangalore and Bangalore will welcome you !

Changing Text Case

toUpperCase(), toLowerCase()

toUpperCase()

A string is converted to upper case with toUpperCase():

var text1 = "Hello World";
var text2 = text1.toUpperCase(); 
console.log(text2);

// HELLO WORLD

toLowerCase()

A String is converted to lower case with toLowerCase():

var text1 = "Hello World";
var text2 = text1.toLowerCase(); 
console.log(text2);

// hello world

Joining two or More Strings

concat()

concat() joins two or more strings:

var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);
console.log(text3);

// Hello World 

Split a String

The split() method splits a string into a substrings array and returns the new array.

The string is split between every character if the seperator is (“”);

The original string is left unchanged after this method.

Syntax : `string.split(seperator, limit)

seperator: (optional). Specifies the regular expression or the character, for splitting the string. The entire string will be returned if omitted.

limit : (optional) An integer that specifies the splits number

In this example, array is limited for 2 values:

var str = "Whats your name?";
var result = string.split(" ", 2);

document.writeln(result);
// Whats,your

In this example, letter “a” is used to seperate the string:

var str = "Whats your name?";
var result = string.split("a");

document.writeln(result);
// Wh,ts your n,me?

Trimming a String

trim()

The trim() method removes whitespaces from both sides of a string:


var str = "     Good Morning ! ";
console.log(str.trim());

// Good Morning

Extracting String Characters

charAt(), charCodeAt()

charAt()

Return character at specified position.

const str = 'JavaScript is amazing';

console.log(str.charAt()); // 'J' 
console.log(str.charAt(11)); // 'i'
console.log(str.charAt(14)); // 'a'
console.log(str.charAt(110)); // ''

charCodeAt()

The charCodeAt() method returns the unicode of the character at a specified index in a string:

The method returns a UTF-16 code ( an integer betn 0 and 65535)


var str = "Hello World";
str.charCodeAt(0);

// 72

Determining Position in the given String

startsWith(), endsWith()

startsWith()

Check if string starts with specified character(s).

const str = 'Javacript is amazing';

console.log(str.startsWith('Javascript')); // true
console.log(str.startsWith('Java')); // true
console.log(str.startsWith('javascript)); // false 

// position is optional 
// if not specified the default value is 0
console.log(str.startsWith('Script', 4)); // true
console.log(str.startsWith('SCRIPT', 4)); // false

endsWith()

Check if string ends with specified character(s).

const str = 'JavaScript is amazing';

// check if ends with 'amazing'
console.log(str.endsWith('amazing')); // true
console.log(str.endsWith('ing')); // true 
console.log(str.endsWith('Amazing')); // false 

// length is optional 
// if not specified, th default value is length of the string 
console.log(str.endsWith('is', 13)); // true
console.log(str.endsWith('i', 13)); // false
console.log(str.endsWith('s', 13)); // true