JavaScript String
The
String global object is a constructor for strings, or a sequence of characters.
There are 2 ways to create string in JavaScript
- By string literal
- By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using string literal is given below:
2) By string object (using new keyword)
The syntax of creating string object using new keyword is given below:
var stringname=new String("string literal");
JavaScript String Methods
Let's see the list of JavaScript string methods with examples.
- charAt(index)
he JavaScript String charAt() method returns the character at the given index.var str="javascript";
document.write(str.charAt(2));
- concat(str)
The JavaScript String concat(str) method concatenates or joins two strings.var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
- indexOf(str)
The JavaScript String indexOf(str) method returns the index position of the given string.var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
document.write(n);
- lastIndexOf(str)
The JavaScript String lastIndexOf(str) method returns the last index position of the given string.var s1="javascript from javatpoint indexof";
var n=s1.lastIndexOf("java");
document.write(n);
- toLowerCase()
The JavaScript String toLowerCase() method returns the given string in lowercase letters.var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
- toUpperCase()
The JavaScript String toUpperCase() method returns the given string in uppercase letters.var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
- slice(beginIndex, endIndex)
The JavaScript String slice(beginIndex, endIndex) method returns the parts of string from given beginIndex to endIndex. In slice() method, beginIndex is inclusive and endIndex is exclusive.var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
- trim()
The JavaScript String trim() method removes leading and trailing whitespaces from the string.var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
Comments
Post a Comment