String in Java
A string is a collection of characters that enclosed either within single quotes (‘) or double quotes (“).
Example
var name = ‘Shairy’; // Single quoted string
var name = “Shairy!”; // Double quoted string
Different properties and methods are used on string values.
Getting the Length of a String
To count the number of characters in a string; length property is used to tell us the length of the string.
Example
var str1 = “This is a JavaScript String Tutorial.”;
alert (str1.length);
Finding a String Inside Another String
indexOf() and lastIndexOf() method is used to find a string within another string. This method returns the first occurrence of a specified string within a string and last occurrence of a specified string within a string respectively and return -1 if the substring is not found.
Example
var str = ” This is a JavaScript String Tutorial. JavaScript Method are given below”;
var pos = str.indexOf(“JavaScript “);
alert(pos);
var pos1 = str.lastIndexOf(“JavaScript “);
alert(pos);
Searching for a Pattern Inside a String
Search() method is used to search a particular piece of text or pattern inside a string. This method is similar to indexOf() method but can also take a regular expression as its argument to provide advanced search capabilities.
Example
var str = “Java Script is not similar to java Language.”;
// Case sensitive search
var pos2 = str.search(“Java “);
alert(pos2);
// Case insensitive search using regexp
var pos3 = str.search(/color/i);
alert(pos3);
very nice teacher