一些旧版本的浏览器或旧浏览器本身不支持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, "");}
登录后复制
在上面的语法中,我们使用正则表达式来替换字符串开头和结尾的空格。
立即学习“Java免费学习笔记(深入)”;
正则表达式解释
^ – 这是字符串的开头。
s+ – 代表一个或多个空格。
| – 它代表“OR”运算符。
s+$ – 它表示字符串末尾的空格。
g – 它告诉我们删除所有匹配项。
示例(使用内置 string.trim() 方法)
在下面的示例中,我们使用了 String 对象的内置 trim() 方法来删除字符串开头和结尾的空格。
Using the trim() method without polyfill in JavaScript
let content = document.getElementById('content'); let str = " This is string with white spaces! "; content.innerHTML += "The original string is :-" + str + ".
"; let trimmed = str.trim(); content.innerHTML += "The trimmed string using trim() method is :-" + str + ".
";
登录后复制
示例(为 string.trim() 方法实现了 polyfill)
在下面的示例中,我们实现了polyfill,以使用正则表达式修剪字符串。我们编写了正则表达式,用空字符串替换开头和结尾的空格。
Using the trim() method with polyfill in JavaScript
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 + ".
"; let trimmed = str.trim(); content.innerHTML += "The trimmed string using trim() method is :-" + str + "
";
登录后复制
示例
在下面的示例中,我们使用 for 循环来查找字符串的第一个和最后一个有效字符的索引。我们创建了一个包含代表空白的不同字符的数组。之后,第一个 for 循环遍历字符串的字符,检查不在“spaces”数组中的第一个字符,并将该索引存储在 start 变量中。此外,它以相同的方式从最后一个字符中查找第一个有效字符。
最后,我们使用了 slice() 方法来获取从“start”位置开始到“end”位置结束的子字符串。
Using the trim() method with polyfill in JavaScript
let content = document.getElementById('content'); String.prototype.trim = function () { const spaces = ["s", "", "", " ", "", "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 -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 + ".
"; let trimmed = str.trim(); content.innerHTML += "The trimmed string using trim() method is :-" + str + "
";
登录后复制
用户在本教程中学习了如何实现 string.trim() 方法的 polyfill。我们已经看到了两种为trim()方法实现polyfill的方法。第一种方法使用正则表达式和replace()方法。第二种方法是简单的方法,使用 for 循环、slice() 和includes() 方法。
以上就是在 JavaScript 中为 String.prototype.trim() 方法实现 polyfill的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2694515.html