发布于 2026-01-06 4 阅读
0

如何在 JavaScript 中修剪字符串

如何在 JavaScript 中修剪字符串

替代文字

从字符串中删除空格非常简单。要删除开头的空格,可以使用 `\f` trimStart()。要删除结尾的空格,可以使用 `\t` trimEnd()。或者使用 `\f` 删除所有空格trim()。🙌

const string = "   hi   ";

string.trimStart(); // "hi   "
string.trimEnd();   // "   hi"
string.trim();      // "hi"

修剪返回值

所有修剪方法都会返回一个新的字符串。这意味着你的原始字符串将保持不变。

const string = "   hi   ";

string.trimStart(); // "hi   "
string.trimEnd();   // "   hi"
string.trim();      // "hi"

string;            // "   hi   "

什么是空白空间

这样trim就能移除空格。所以,移除的空格是由以下原因产生的:

  • 空间
  • 标签页
  • 不间断空间
  • 换行符

修剪终结者角色

你可能想知道什么是换行符。那么,让我们来看一些例子。

'hi \n'.trim(); // "hi"

'hi \t'.trim(); // "hi"

'hi \r'.trim(); // "hi"

多行字符串

在 JavaScript 中,你可以使用模板字面量轻松创建多行字符串。所以如果你想知道trim它是否支持多行字符串,答案是肯定的 👍

const multiLine = `
hi


`;

multiline.trim(); // "hi"

删除多个单词

请记住,trim此功能仅处理开头和结尾的空格,不会删除单词之间的空格。

'  hi there  '.trim(); // "hi there"

多行多词

对于多行文本,它只会剪掉第一个单词的开头和最后一个单词的结尾。

const multiLine = `
hi

there


`;

// Returns

"hi

there"

删除别名

trimStart 与 trimLeft

trimStart删除字符串开头的空格。因此,从字符串开头到第一个非空格字符之间的所有空格都将被删除。

你可能还会看到有人使用trimLeft()。嗯,那是因为它是一个别名。它的作用是一样的。

const string = "   hi   ";

string.trimStart(); // "hi   "
string.trimLeft();  // "hi   "

trimEnd 与 trimRight

trimEnd移除字符串末尾的空格。因此,字符串末尾的所有空格都将被删除。此方法的别名是 ` trimRight().`。同样,它们的功能相同。

const string = "   hi   ";

string.trimEnd();   // "   hi"
string.trimRight(); // "   hi"

我应该用哪一个?

那么应该使用哪一个呢?让我们来看看ECMAScript 规范是怎么说的:

建议使用trimStart`nad`属性。`and`属性主要是为了与旧代码兼容而提供的。建议在新 ECMAScript 代码中使用 `trimStart` 属性trimEndtrimLefttrimRight

trimStarttrimEnd了👑

为什么会有别名?

所以,最初引入了 ` trimLeftand` 和 ` trimRightor`。然而,委员会决定提议将措辞改为 ` trimStartand` trimEnd。这是因为这样与他们其他的内置方法(padStart例如`and` 和 `or`)更加一致padEnd。我认为这很有道理,我认为一致性至关重要,使用相同的语言有助于减少混淆。

但出于网页兼容性的考虑,他们保留了旧方法(` trimLeftand` 和 ` trimRight)作为别名。所以如果你的代码使用了旧方法,没问题,它们仍然可以正常工作👍。不过,如果条件允许,我建议你将其更改为使用官方方法,而不是别名,这样你的代码库中就不会存在两种不同的方法了。记住,保持一致性至关重要😎

修剪方法用例

修剪

我主要用它trim()来删除表单输入框中的空格,非常方便👍

<input type="text" id="search" />
const inputValue = document.getElementById('search').value.trim();

你还可以用它来删除句子中多余的空格,并进行格式化。本质上就是让你的句子更美观💅

const uglySentence = "One  Two   Three Four   ";

const prettySentence = uglySentence
    .split(' ') // ["One", "", "Two", "", "", "Three", "Four", "", "", ""]
    .filter(word => word) // ["One", "Two", "Three", "Four"]
    .join(' '); // "One Two Three Four"

// ✅ Result
console.log(prettySentence); // "One Two Three Four"

trimStart

我以前没用过这个功能。但我能看出它的实用之处。比如,在 Markdown 文件中,你肯定希望保留开头的空格,但结尾的空格可能需要自动删除,以免给用户造成困惑或意想不到的显示效果。

- List Item
  - Sub List Item
  - Sub List Item

修剪结束

我目前没有很好的例子。但如果继续以 Markdown 文件为例,我们可能需要禁止嵌套列表项,但同时又希望保留末尾的空格。在 Markdown 中,如果插入两个空格,就会创建一个换行符。·为了方便理解,我将用点号 (.) 来表示空格。

Markdown 不会在此处创建换行符。

hi
there

// Result
hi there

要强制换行,可以添加 2 个空格。

hi··
there

// Result
hi
there

因此,了解了这一点后,您可能不想删除末尾的空格。但是,您仍然希望删除嵌套列表。在这种情况下,`trimStart` 函数或许正合您意。

浏览器支持

对 的支持非常棒!但是,对和 的trim()支持有点有限,这是因为它们是后来才引入的。trimStarttrimEnd

浏览器 修剪 trimStart 修剪结束
铬合金
火狐浏览器
狩猎之旅
边缘
Internet Explorer

社区意见

@ArtesEveni

const string = '  hi   ';
string.replace(/ /g, ''); // "hi"

👆 注意:此方法会移除字符串中的所有空格。要进行修剪,请使用以下代码:

let str = '      Samantha Ming      ';
let trimmedStr = str.replace(/^\s+ | \s+$/g, '');

console.log(trimmedStr); // "Samantha Ming"

谢谢@Jalaj

资源


感谢阅读❤
欢迎关注我的Instagram | Twitter | SamanthaMing.com

文章来源:https://dev.to/samanthaming/how-to-trim-string-in-javascript-1aa9