在 JavaScript 中复制 Python Stripe 方法
    
    Mehvish Ashiq
    2023年10月12日
    
    JavaScript
    JavaScript Stripe
    
本教程讨论在 JavaScript 中模拟 Python 的 stripe() 方法。Python stripe() 从字符串的两个边缘(开始和结束)删除空格。
例如,"           hello " 变成 "hello"。为了在 JavaScript 中获得相同的效果,我们可以使用 trim() 和 replace() 方法。
trim() 是 ECMAScript5 (ES5) 的一个功能,它从字符串的开头和结尾删除空格。它可以在所有最新的浏览器中轻松使用。
trim() 有两种变体,可以仅从字符串的开头或从字符串的末尾丢弃空格。为此,我们可以使用 trimStart() 和 trimEnd() 分别消除开头和结尾的空格。
如果我们还想删除所有空格,包括将一个单词与另一个单词分开的空格,那么我们可以使用带有正则表达式的 replace() 方法。
replace() 函数在字符串中查找特定值,替换它并返回一个新字符串,而不更新原始字符串。
在 JavaScript 中复制 Python stripe() 方法
var str1 = ' hello world';
var str2 = 'hello world ';
var str3 = ' hello world ';
var str4 = '           hello world ';
console.log(str1.trimStart());
console.log(str2.trimEnd());
console.log(str3.trim());
console.log(str4.trim());
输出:
"hello world"
"hello world"
"hello world"
"hello world"
如果我们不想使用内置的 trim() 函数,我们可以通过利用 String.prototype 来使用以下代码。它执行与 trim() 函数相同的功能,但使用带有正则表达式的 replace() 方法来实现目标。
String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, '');
};
String.prototype.lefttrim = function() {
  return this.replace(/^\s+/, '');
};
String.prototype.righttrim = function() {
  return this.replace(/\s+$/, '');
};
var text = '    hello world  ';
console.log(text.lefttrim());
console.log(text.righttrim());
console.log(text.trim());
输出:
"hello world  "
"    hello world"
"hello world"
这是替换所有空格的解决方案。这种方法对于删除联系人号码中的空格非常有用。
var text = '    +92 345 254 2769      ';
console.log(text.replace(/\s/g, ''));
输出:
"+923452542769"
在 JavaScript 中使用 jQuery 模拟 Python stripe() 方法
var str1 = ' hello world';
var str2 = 'hello world ';
var str3 = ' hello world ';
var str4 = '           hello world ';
console.log($.trim(str1));
console.log($.trim(str2));
console.log($.trim(str3));
console.log($.trim(str4));
输出:
"hello world"
"hello world"
"hello world"
"hello world"
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
作者: Mehvish Ashiq
    
