Home >Web Front-end >JS Tutorial >Use JavaScript's built-in functions to handle string operations
Use JavaScript built-in functions for string operations
In JavaScript, there are many built-in functions that can be used to handle string operations. These functions can help us change the case of strings, find substrings, replace characters, and more. This article will introduce some commonly used string manipulation functions and give corresponding code examples.
These two functions are used to convert strings to uppercase and lowercase respectively. For example:
var str = "Hello World!"; console.log(str.toUpperCase()); // 输出 "HELLO WORLD!" console.log(str.toLowerCase()); // 输出 "hello world!"
indexOf() is used to find the first occurrence of a substring in a string, and lastIndexOf() is to find the last occurrence. If the substring is found, the function returns its index value; if not, it returns -1.
var str = "Hello World!"; console.log(str.indexOf("o")); // 输出 4 console.log(str.lastIndexOf("o")); // 输出 7 console.log(str.indexOf("x")); // 输出 -1
The slice() function is used to extract part of the content from the string. It accepts two parameters, the starting position and the ending position (excluding the characters at this position). If only one parameter is provided, the default is to extract from that position to the end of the string.
var str = "Hello World!"; console.log(str.slice(0, 5)); // 输出 "Hello" console.log(str.slice(6)); // 输出 "World!"
replace() function is used to replace certain characters in a string. It accepts two parameters, the first parameter is the substring to be replaced (can be a regular expression), and the second parameter is the new string after replacement.
var str = "Hello World!"; console.log(str.replace("Hello", "Hi")); // 输出 "Hi World!"
The split() function is used to split a string into an array. It accepts one parameter that specifies the delimiter. The delimiter can be a string or a regular expression.
var str = "Hello World!"; console.log(str.split(" ")); // 输出 ["Hello", "World!"]
Thetrim() function is used to remove spaces at both ends of a string. It does not accept any parameters.
var str = " Hello World! "; console.log(str.trim()); // 输出 "Hello World!"
To sum up, JavaScript’s built-in functions provide rich string manipulation functions. Proficiency in these functions can make string processing more efficient and convenient. I hope this article can be helpful to everyone.
The above is the detailed content of Use JavaScript's built-in functions to handle string operations. For more information, please follow other related articles on the PHP Chinese website!