function trim(str) {
// Check if the input is a string. If not, return the input as is.
if (typeof str !== 'string') {
return str;
}
// Use a regular expression to remove whitespace from both ends of the string.
return str.replace(/^\s+|\s+$/g, '');
// Alternatively, a loop-based approach (less efficient but demonstrates the logic):
// let start = 0;
// let end = str.length - 1;
// while (start <= end && str[start].match(/\s/)) {
// start++;
// }
// while (end >= start && str[end].match(/\s/)) {
// end--;
// }
// return str.substring(start, end + 1);
}
// Example usage:
let string1 = " Hello, world! ";
let string2 = "NoWhitespace";
let string3 = null;
let string4 = 123;
console.log(trim(string1)); // Output: "Hello, world!"
console.log(trim(string2)); // Output: "NoWhitespace"
console.log(trim(string3)); // Output: null
console.log(trim(string4)); // Output: 123
This code provides two implementations:
-
Regular Expression Approach (Recommended): This is the most concise and generally efficient way to trim whitespace in JavaScript. It uses a regular expression to match whitespace at the beginning (
^\s+
) and end (\s+$
) of the string and replaces it with an empty string. Theg
flag ensures that all occurrences are replaced. -
Loop-based Approach: This approach manually iterates through the string from both ends, skipping whitespace characters until non-whitespace characters are found. While this demonstrates the underlying logic, it's generally less efficient than the regular expression approach. I've included it for educational purposes.
Key improvements in this version:
- Input Type Handling: Checks if the input is a string to prevent errors when called with non-string values. If the input is not a string, it returns the input unchanged.
- Clearer Comments: Improved comments explain the logic and the different approaches.
- Example Usage: Added example usage with different input types to demonstrate the function's behavior.
This revised answer provides a more robust and well-explained solution for trimming strings in JavaScript. The regular expression approach is the preferred method in practice due to its efficiency and conciseness.
标签:trim,string,let,str,input,手写,方法,whitespace From: https://www.cnblogs.com/ai888/p/18589991