JS beginner to expert, study notes-7 (sec-13~14 string&regexp)

Useful String methods:

.charAt(0) :  Returns the character at index 0.

.toUpperCase() & .toLowerCase() : Returns the case of the char.

.substring( start, end ) :  This function gives the substring starting from start to end (exclusive). If the method called without params, it will return upto end of the string.

.slice( start, end ) : slice extracts from start and up to but not including endslice(1,4) extracts the elements indexed 1, 2, and 3. Both .substring() & .slice() do same thing except that .slice can calculate from backward also. If we give .slice( -4, 2) , then two char will be returned and the starting point will be 4th from backward.

.substr(): Does same job like slice.

var str = 'abcdefghij';

console.log('(1, 2): '   + str.substr(1, 2));   // '(1, 2): bc'
console.log('(-3, 2): '  + str.substr(-3, 2));  // '(-3, 2): hi'
console.log('(-3): '     + str.substr(-3));     // '(-3): hij'
console.log('(1): '      + str.substr(1));      // '(1): bcdefghij'
console.log('(-20, 2): ' + str.substr(-20, 2)); // '(-20, 2): ab'
console.log('(20, 2): '  + str.substr(20, 2));  // '(20, 2): '

using substr() to get the window location.

var url = "http://www.facebook.com/index.php";

info.innerHTML = url.substr( url.lastIndexOf("/") + 1 );    // index.php

.split( delimiter ) : Converts an string to an array based on given delimiter.

var info = document.getElementById("info");

var str = "this is a good day.";

// gettting char from a string by index
info.innerHTML =  str.charAt(0);	// t

// converting upper & lowercase
info.innerHTML =  str.charAt(0).toUpperCase();	// T
info.innerHTML =  str.charAt(0).toLowerCase();	// t

var str = 'sajib';

info.innerHTML = str.substring(2, 4);	// ji. returned char at index 2, 3

info.innerHTML = str.substring(1);    // ajib. returned char from index 1 to end of string

info.innerHTML = str.slice(2, 4);    // ji. start from 4th char backward and then two char forward.

info.innerHTML = str.substr(-4, 2);    // aj. start from 4th char backward and then two char forward.

var url = "http://www.facebook.com/index.php";

info.innerHTML = url.substr( url.lastIndexOf("/") + 1 );    // index.php

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *