JavaScript provides a wide range of string methods to manipulate and work with text efficiently. Here’s a comprehensive list:
Basic String Methods
length
– Returns the length of a string.
let text = "Hello, JavaScript!";
console.log(text.length); // Output: 18
charAt(index)
– Returns the character at a specific index.
console.log("Hello".charAt(1)); // Output: "e"
charCodeAt(index)
– Returns the Unicode value of a character at a given index.
console.log("Hello".charCodeAt(1)); // Output: 101 (Unicode for 'e')
at(index)
– Similar to charAt()
, but supports negative indexing.
console.log("Hello".at(-1)); // Output: "o"
String Manipulation Methods
toUpperCase()
– Converts a string to uppercase.
console.log("hello".toUpperCase()); // Output: "HELLO"
toLowerCase()
– Converts a string to lowercase.
console.log("HELLO".toLowerCase()); // Output: "hello"
trim()
– Removes whitespace from both ends of a string.
console.log(" Hello World! ".trim()); // Output: "Hello World!"
trimStart()
/ trimEnd()
– Removes whitespace from the start or end.
console.log(" Hello".trimStart()); // Output: "Hello"
console.log("Hello ".trimEnd()); // Output: "Hello"
JavaScript provides a variety of string methods. Here’s a list of commonly used string methods:
charAt(index): Returns the character at the specified index.
charCodeAt(index): Returns the Unicode of the character at the specified index.
concat(string1, string2, ...): Combines two or more strings.
includes(searchString, position): Checks if a string contains a specified substring.
indexOf(searchValue, fromIndex): Returns the index of the first occurrence of a specified value.
lastIndexOf(searchValue, fromIndex): Returns the index of the last occurrence of a specified value.
match(regexp): Retrieves the matches when matching a string against a regular expression.
replace(searchValue, newValue): Replaces a specified value with another value in a string.
search(regexp): Tests for a match in a string and returns the index of the match.
slice(start, end): Extracts a section of a string and returns it as a new string.
split(separator, limit): Splits a string into an array of substrings.
substring(start, end): Returns a part of the string between two specified indices.
toLowerCase(): Converts a string to lowercase letters.
toUpperCase(): Converts a string to uppercase letters.
trim(): Removes whitespace from both ends of a string.
valueOf(): Returns the primitive value of a string object.
No comments:
Post a Comment