String Methods in Java
Extracting a Substring from a String
slice() method is used to extract a part or substring from a string. This method takes 2 parameters: like str.slice(startIndex, endIndex).
Example
var str = “The Best IT Company in Ludhiana is ershairykalra.”;
var subStr = str.slice(4, 19);
document.write(subStr);
Extracting a Fixed Number of Characters from a String
JavaScript also provide the substr() method which is similar to slice() with a small difference, the second parameter specifies the number of characters to extract instead of ending index, like str.substr(startIndex, length). If length is 0 or a negative number, an empty string is returned. The following example demonstrates how it works:
Example
var str = ” The Best IT Company in Ludhiana is ershairykalra.”;
document.write(str.substr(4, 15));
Replacing the Contents of a String
Replace() method is used to replace part of a string with another string and returns a new string. This method takes two parameters like str.replace(regexp|substr, newSubstr).
- First is regular expression to match or substring to be replaced
- Second is a replacement string
Example
var str = ” The Best IT Company in Ludhiana is ershairykalra company.”;
var result = str.replace(“Company”, “Institute”);
alert(result);
Replace() method is case sensitive and pick first string only; for case-insensitive we use a regular expression (regexp) with an i modifier
var str = ” The Best IT Company in Ludhiana is ershairykalra company.”;
var result = str.replace(/company /i, ” Institute “);
alert(result);
if we want to replace all string in a case-insensitive manner you can use the g modifier along with the i modifier, like this:
Example
var str = ” The Best IT Company in Ludhiana is ershairykalra company.”;
var result = str.replace(/company /ig, ” Institute “);
alert(result);
Converting a String to Uppercase or Lowercase
toUpperCase() and toLowerCase methods are used to convert a string to uppercase and lowercase
Example
var str = “Shairy Kalra”;
var result = str.toUpperCase();
document.write(result);
var result = str.toLowerCase();
document.write(result);
Accessing Individual Characters from a String
charAt() method is used to access individual character from a string, like str.charAt(index).
Example
var str = “Shairy Kalra”;
document.write(str.charAt(6));