JavaScript 为String.prototype.trim()方法实现兼容性填充

JavaScript 为String.prototype.trim()方法实现兼容性填充

在本文中,我们将学习如何为JavaScript中的 string.prototype.trim() 方法实现兼容性填充。

兼容性填充是一种计算机代码片段,用于在浏览器中实现尚未支持的功能。这可能是因为您正在使用的浏览器版本较旧,或者新版本的浏览器没有该功能。

我们将讨论JavaScript中字符串支持的 trim() 方法,并且还将实现我们自己的版本。 trim() 方法从字符串的两个端点(左端点和右端点)删除所有空格,并返回剩余的字符串。字符串中除空格以外的内容保持不变。

示例:

Javascript

<script> 
    const str = "   Hello world!   "; 
  
    console.log(str);    
    console.log(str.trim());   
</script>

输出:

"   Hello world!"
"Hello world!"

String.prototype.trim()方法: 让我们为 trim() 方法创建一个简单的polyfill。

示例1: 以下代码使用正则表达式来移除空格。

JavaScript

<script> 
    const trim = (str) => { 
  
        // let's breakdown the above regex 
        // '/s+' represents one or more  
        // whitespace characters 
        // '^' represents characters at the  
        // beginning of the expression 
        // '' represents characters at  
        // the end of the expression 
        // we replace all the whitespace  
        // characters at the beginning and 
        // the end of the string with "" (empty string) 
        return str.replace(/^\s+|\s+/g, ""); 
    } 
  
    let s = "  Geeksforgeeks"; 
    console.log(s); 
    console.log(trim(s)); 
</script>

输出:

" Geeksforgeeks "
" Geeksforgeeks "

示例2: 以下代码循环遍历字符串,并分别从字符串的开头和末尾删除空格。

Javascript

<script> 
  
    // Declare a whitespaces array  
    const whitespaces = [" ", "", "\s", "\t", "\n", "\u3000"]; 
  
    const trim = (str) => { 
        let stringBeg = 0, stringEnd = str.length; 
  
        // Find the index from the beginning of the string  
        // which is not a whitespace 
        for (let i = 0; i < str.length; i++) { 
            if (whitespaces.indexOf(str[i]) === -1) { 
                stringBeg = i; 
                break; 
            } 
        } 
  
        // Find the index from the end of the string 
        // which is not a whitespace 
        for (let j = str.length - 1; j >= 0; j--) { 
            if (whitespaces.indexOf(str[j]) === -1) { 
                stringEnd = j; 
                break; 
            } 
        } 
  
        // Return the string between the 2 found indices 
        return str.slice(stringBeg, stringEnd + 1); 
    } 
  
    let s = "  Geeksforgeeks"; 
    console.log(s); 
    console.log(trim(s)); 
</script>

输出:

"  Geeksforgeeks"
"Geeksforgeeks"

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程