Sunday 12 June 2016

Javascript - String

JavaScript strings are used for storing and manipulating text.It is an object that represents sequence of characters.

A JavaScript string simply stores a series of characters like "John Smith".
A string can be any text inside quotes. You can use single or double quotes.

Eg:
var name= "Bob";
var name= 'Bob';

String length
Below is the code for find the length of  a string

var name = "John Smith";
var val = name.length;

JavaScript String Methods
Let's see the list of JavaScript string methods with examples.

  • charAt(index)
  • concat(str)
  • indexOf(str)
  • lastIndexOf(str)
  • toLowerCase()
  • toUpperCase()
  • slice(beginIndex, endIndex)
  • trim()
charAt ()

var str="hellowworld";
document.write(str.charAt(4)); 

output: o

concat(str)

var str1="hello";
var str2="world";
var str3=str1.concat(str2);
document.write(str3); 

output: hello world

indexOf(str)

var str1="helloworld from javascript";
var num=str1.indexOf("from");
document.write(num);  

output: 11

lastIndexOf(str)

var str1="hellowworld from javascript";
var num=str1.lastIndexOf("java");
document.write(num);  

output: 16

toLowerCase()

var str1="JavaScript toLowerCase Example";
var str2=str1.toLowerCase();
document.write(str2); 

Output: javascript tolowercase example

toUpperCase()

var str1="JavaScript toUpperCase Example";
var str2=str1.toUpperCase();
document.write(str2); 

Output: JAVASCRIPT TOUPPERCASE EXAMPLE

slice()

var str1="abcdefgh";
var str2=str1.slice(2,5);
document.write(str2); 

output: cde

trim()

var str1="     javascript trim example    ";
var str2=str1.trim();
document.write(str2); 

output: javascript trim example

2 comments :

  1. the blog is very interesting and will be much useful for us. thank you for sharing the blog with us. please keep on updating.
    Informatica Training in Chennai Adyar

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete