Js String Methods in JavaScript
? JavaScript String Methods
JavaScript provides many built-in string methods to manipulate and work with text data.
Common String Methods
| Method | Description | Example | Output |
|---|---|---|---|
length | Returns the length of the string | "hello".length | 5 |
toUpperCase() | Converts string to uppercase | "hello".toUpperCase() | "HELLO" |
toLowerCase() | Converts string to lowercase | "HELLO".toLowerCase() | "hello" |
indexOf(substring) | Returns first index of substring or -1 if not found | "hello".indexOf("e") | 1 |
lastIndexOf(substring) | Returns last index of substring or -1 | "hello".lastIndexOf("l") | 3 |
slice(start, end) | Extracts substring between start and end indices | "hello".slice(1,4) | "ell" |
substring(start, end) | Similar to slice, but doesn’t accept negative indexes | "hello".substring(1,4) | "ell" |
substr(start, length) | Extracts substring from start position of given length | "hello".substr(1,3) | "ell" |
trim() | Removes whitespace from both ends | " hello ".trim() | "hello" |
split(separator) | Splits string into an array by separator | "a,b,c".split(",") | ["a", "b", "c"] |
replace(search, replace) | Replaces first occurrence of search string with replace | "hello".replace("l", "L") | "heLlo" |
includes(substring) | Checks if string contains substring (returns true/false) | "hello".includes("ll") | true |
startsWith(substring) | Checks if string starts with substring | "hello".startsWith("he") | true |
endsWith(substring) | Checks if string ends with substring | "hello".endsWith("lo") | true |
charAt(index) | Returns character at specified index | "hello".charAt(1) | "e" |
charCodeAt(index) | Returns UTF-16 code of character at index | "hello".charCodeAt(1) | 101 |
Example:
let str = " Hello, World! ";console.log(str.length); // 16console.log(str.trim()); // "Hello, World!"console.log(str.toUpperCase()); // " HELLO, WORLD! "console.log(str.indexOf("World")); // 8console.log(str.slice(2, 7)); // "Hello"console.log(str.replace("World", "JS")); // " Hello, JS! "console.log(str.split(",")); // [" Hello", " World! "]console.log(str.includes("Hello")); // trueIf you want, I can give you examples on regular expressions with strings or template literals next!