1.String :
JavaScript strings are for storing and manipulating text.In JavaScript, a string is a sequence of characters enclosed in single or double quotes. For example:
let firstName = 'Megha';
let lastName = "khatri";
2. JavaScript String Methods :
Strings have several built-in methods that can be used to manipulate and retrieve information from strings. Some examples include:
1. .length
The length
property returns the length of a string:
let name = "Megha khatri";
console.log(name.length); //output 12
2. .concat()
:
This method concatenates (joins) two or more strings and returns a new string.
let firstName ="Megha";
let lastName = "Khatri";
let fullName = firstName.concat(" ",lastName);
console.log(fullName); // output "Megha Khatri"
3. .toUpperCase()
:
This method converts all the characters in a string to uppercase.
let text = 'good morning';
console.log(text.toUpperCase()); //output 'GOOD MORNING'
4. .toLowerCase()
:
This method converts all the characters in a string to lowercase.
let text = 'GOOD MORNING';
console.log(text.toLowerCase()); //output 'good morning'
4. .indexOf()
:
This method returns the index of the first occurrence of a specified string value.
let text ='good noon';
console.log(text.indexOf('noon')); // output 5
5. .slice()
:
This method extracts a part of a string and returns a new string.The method takes 2 parameters: start position, and end position (end not included).
For example : Slice out a portion of a string from position 7 to position 13:
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13); //output 'Banana'
6..substr()
:
substr()
is similar to slice()
.
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
The difference is that the second parameter specifies the length of the extracted part.
7. replace()
The replace()
method replaces a specified value with another value in a string.The replace()
method returns a new string.The replace()
method replaces only the first match
let text = "Please visit again!";
let newText = text.replace("again", "again in future");
8. trim()
:
The trim()
method removes whitespace from both sides of a string:
let text1 = " Hello World! ";
let text2 = text1.trim();
9. trimStart()
:
The trimStart()
method works like trim()
, but removes whitespace only from the start of a string.
let text1 = " Hello World! ";
let text2 = text1.trimStart();
10. trimEnd()
The trimEnd()
method works like trim()
, but removes whitespace only from the end of a string.
let text1 = " Hello World! ";
let text2 = text1.trimEnd();