JavaScript String Methods code
Here are some commonly used JavaScript string methods:
length
: Returns the length of a string.const str = 'Hello, World!'; console.log(str.length); // Output: 13
toUpperCase()
: Converts a string to uppercase.const str = 'Hello, World!'; console.log(str.toUpperCase()); // Output: HELLO, WORLD!
toLowerCase()
: Converts a string to lowercase.const str = 'Hello, World!'; console.log(str.toLowerCase()); // Output: hello, world!
indexOf()
: Returns the index of the first occurrence of a specified value in a string.const str = 'Hello, World!'; console.log(str.indexOf('World')); // Output: 7
slice()
: Extracts a part of a string and returns a new string.const str = 'Hello, World!'; console.log(str.slice(7)); // Output: World! console.log(str.slice(7, 12)); // Output: World
replace()
: Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.const str = 'Hello, World!'; console.log(str.replace('World', 'Universe')); // Output: Hello, Universe!
split()
: Splits a string into an array of substrings.const str = 'Hello, World!'; console.log(str.split(',')); // Output: ['Hello', ' World!']
trim()
: Removes whitespace from both ends of a string.const str = ' Hello, World! '; console.log(str.trim()); // Output: Hello, World!
These are just a few of the many available JavaScript string methods.