在 JavaScript 中为 String.prototype.trim() 方法实现 polyfill

一些旧版本的浏览器或旧浏览器本身不支持JavaScript新发展的功能。例如,如果您使用的是非常旧的浏览器版本,它不支持 ES10 版本 JavaScript 的功能。例如,某些版本的浏览器不支持 ES10 版本的 JavaScript 中引入的 Array.falt() 方法来展平数组。
在这种情况下,我们需要实现用户定义的方法来支持旧浏览器版本的功能。在这里,我们将为 String 对象的trim()方法实现polyfill。
语法
用户可以按照下面的语法使用正则表达式为 string.prototype.trim() 方法实现polyfill。
String.prototype.trim = function (string) {
return str.replace(/^\s+|\s+$/g, "");
}
在上面的语法中,我们使用正则表达式来替换字符串开头和结尾的空格。
正则表达式解释
^ - 这是字符串的开头。
\s+ - 代表一个或多个空格。
| - 它代表“OR”运算符。
\s+$ - 它表示字符串末尾的空格。
g - 它告诉我们删除所有匹配项。
示例(使用内置 string.trim() 方法)
在下面的示例中,我们使用了 String 对象的内置 trim() 方法来删除字符串开头和结尾的空格。
<html>
<body>
<h2>Using the trim() method without polyfill in JavaScript</h2>
<div id = "content"> </div>
<script>
let content = document.getElementById('content');
let str = " This is string with white spaces! ";
content.innerHTML += "The original string is :-" + str + ".<br>";
let trimmed = str.trim();
content.innerHTML += "The trimmed string using trim() method is :-" + str + ".<br>";
</script>
</body>
</html>
示例(为 string.trim() 方法实现了 polyfill)
在下面的示例中,我们实现了polyfill,以使用正则表达式修剪字符串。我们编写了正则表达式,用空字符串替换开头和结尾的空格。
<html>
<body>
<h2>Using the <i> trim() method with polyfill </i> in JavaScript</h2>
<div id = "content"> </div>
<script>
let content = document.getElementById('content');
String.prototype.trim = function (string) {
let regex = /^\s+|\s+$/g;
return str.replace(regex, "");
}
let str = "Hi, How are you? ";
content.innerHTML += "The original string is :-" + str + ".<br>";
let trimmed = str.trim();
content.innerHTML += "The trimmed string using trim() method is :-" + str + "<br>";
</script>
</body>
</html>
示例
在下面的示例中,我们使用 for 循环来查找字符串的第一个和最后一个有效字符的索引。我们创建了一个包含代表空白的不同字符的数组。之后,第一个 for 循环遍历字符串的字符,检查不在“spaces”数组中的第一个字符,并将该索引存储在 start 变量中。此外,它以相同的方式从最后一个字符中查找第一个有效字符。
最后,我们使用了 slice() 方法来获取从“start”位置开始到“end”位置结束的子字符串。
<html>
<body>
<h2>Using the <i> trim() method with polyfill </i> in JavaScript</h2>
<div id = "content"> </div>
<script>
let content = document.getElementById('content');
String.prototype.trim = function () {
const spaces = ["\s", "\t", "", " ", "", "\u3000"];
let start = 0;
let end = this.length - 1;
// get the first index of the valid character from the start
for (let m = 0; m < this.length; m++) {
if (!spaces.includes(this[m])) {
start = m;
break;
}
}
// get the first index of valid characters from the last
for (let n = this.length - 1; n > -1; n--) {
if (!spaces.includes(this[n])) {
end = n;
break;
}
}
// slice the string
return this.slice(start, end + 1);
}
let str = " Hi, How are you? ";
content.innerHTML += "The original string is :-" + str + ".<br>";
let trimmed = str.trim();
content.innerHTML += "The trimmed string using trim() method is :-" + str + "<br>";
</script>
</body>
</html>
用户在本教程中学习了如何实现 string.trim() 方法的 polyfill。我们已经看到了两种为trim()方法实现polyfill的方法。第一种方法使用正则表达式和replace()方法。第二种方法是简单的方法,使用 for 循环、slice() 和includes() 方法。
javascript