Hello Readers,
In today's post, we will discuss the String methods and properties in JavaScript. These methods and properties make easy to deal with strings.
Now let's have a look at methods and properties:
- To find the length of a string: We can find the length of string with the help of its built-in property length.
For Example:
var userName = "Andrew";
var strLn = userName.length;
console.log(strLn); // Prints result 6.
- Find a String in a String: there are two methods to find a string in a string. First method is indexOf() and second one is lastIndexOf().
- indexof() method used to find the position of the first appearance of a described text in a string.
For Example:
var strValue = "India is a beautiful country and known for its beautiful culture";
var strIndex = strValue.indexOf('beautiful');
console.log(strIndex); // Returns 11
lastIndexOf() method used to find the position of the last appearance of a described text in a string.
For Example:
var strValue = "India is a beautiful country and known for its beautiful culture;";
var strLastIndex = strValue.lastIndexOf('beautiful');
console.log(strLastIndex); // Returns 47
Note: If the text is not found in above both methods then these methods return -1.
- Searching for a string in a string: To search a specified text in a string we can use search() method. This method returns the position of the text and similar to indexOf() method but search() method is more effective and powerful than search() method.
For example:
var strValue = "India is a beautiful country and known for its beautiful culture";
var strSearch = strValue.search('beautiful');
console.log(strSearch); // Returns 11
- Replace the content of a string: This method use to replace the value of any specified text to another value.
For Example:
var strValue = "India is a beautiful country";
var strReplace = strValue.replace("beautiful","very beautiful");
console.log(strReplace);
This method only replaces the first match but if there will more than one same text in a string then we need to use a regular expression flag "g" to replaces all the match. This regular expression is used for the global match in a string.
For Example:
var strValue = "India is a beautiful country and known for its beautiful culture";
var strReplace = strValue.replace(/beautiful/g,"very beautiful");
console.log(strReplace);
Hope this will help you :)
0 Comment(s)