Vue Js - 从字符串中删除空格

Vue Js - removing spaces from string

Let category = "Baby Dress"

I want it to be trimed by spaces and text into lowercase. the output as "babydress". I used the following code. but it returns "baby dress".

category.trim(" ").toLowerCase()

我需要了解为什么它没有像我预期的那样工作,以及有什么方法可以做到。

它没有按预期工作,因为 .trim 函数用于删除字符串两边的空格,而不是中间的空格。

您可以使用

category.toLowerCase().split(" ").join("")

在这里,我将字母设为小写,将它们分开然后连接起来。

你可以这样做:

category.replace(/\s+/g, '').toLowerCase()

trim方法只去除字符串开头的空格。您需要的是使用正则表达式的替换方法将空格替换为空:

category.replace(/\s/g, "").toLowerCase();