These are some most Important String Methods and their examples:
1. length() : The length method returns the length of a string.
Example:
let txt = 'codingtorque';
let length = txt.length;
console.log(length)
Output:
Output => 12
2. slice(start, end) : slice() extract a part of a string and returns the extracted part in a new string.
Example:
let str = 'codingtorque';
let strSlice = str.slice(0, 6)
console.log(strSlice)
Output:
Output => coding
3. substring(start, end) : substring() is similar to slice() function. The difference is substring cannot accept negative indexes.
Example:
let txt = 'codingtorque';
let length = txt.substring(0, 6);
console.log(length)
Output:
// Output => coding
4. substr(start, length) : substr() is similar to slice(). The difference is, the second parameter specifies the length.
Example:
let str = 'Welcome to @code.scientist';
let replacedStr = str.replace('@code.scientist', '@codingtorque')
console.log(replacedStr)
Output:
Output => Welcome to @codingtorque
5. toUppercase() : toUppercase() simply converts a string into uppercase.
Example:
let str = 'coding torque';
let uppercase = str.toUpperCase() // Converted to uppercase
console.log(uppercase)
Output:
Output => CODING TORQUE
6. toLowercase() : toLowercase() simply converts a string into lowercase.
Example:
let str = 'CodinG Torque';
let lowercase = str.toLowerCase() // Converted to uppercase
console.log(lowercase)
Output:
Output => coding torque
7. concat() : concat() joins two or more strings. For example, if you want to join your first name and last name, you can use concat method to join.
Example:
let text1 = 'Coding';
let text2 = 'Torque';
let combined = text1.concat(' ', text2) // Combined text1 & text2
console.log(combined)
Output:
Output => Coding Torque
8. trim() : trim() method remove whitespaces from both side of a string. For example, if you are copying a text from another websites, there might be an unnecessary white spaces which you want to remove. You can use trim function to remove them.
Example:
let str = ' Coding Torque ';
let trimed = str.trim() // Trimmed Text
console.log(trimed)
Output:
Output => Coding Torque
9. replace() : replace() method replace a specified value with another value in a string and return extracted part.
Example:
let str = 'Welcome to @code.scientist';
let replacedStr = str.replace('@code.scientist', '@codingtorque')
console.log(replacedStr)
Output:
Output => Welcome to @codingtorque
10. split() : A string can be converted into an array using split() method.
Example:
let str = 'Coding Torque';
let splitted = str.split(' ') // Splitted Text in Array
console.log(splitted)
Output:
Output => ['Coding', 'Torque']