cloudant中的JS trim()函数

JS trim() function in cloudant

本文关键字:函数 trim 中的 JS cloudant      更新时间:2023-09-26

我在Cloudant中构建了一个搜索索引。我使用trim()来删除字符串中的空格。然而,它不起作用。

我该怎么做?

更新:

我有一个JSON对象

...
    "attributeArray": [
      {
        "name": "this is  a       web     authentication"
      }
    }
...

我已经成功提取了"name"。我想删除"名称"中的空格,然后为文档创建搜索索引。假设"name"已经被提取。

var index=name.trim();
Index("default", index);

当我查询时,系统显示:

{
"id": "06xxxx",
"fields": [
" this is  a       web     authentication"
]
}

我得出结论,函数trim()不起作用。

附言:一个小问题,所以不需要解释整个事情。

根据定义,trim()函数只会删除字符串中的前导和尾部空白,这可能不是您在这种情况下所需要的。

如果您想删除所有空白,您可以考虑通过replace()函数使用正则表达式替换:

// This will remove all white-space from your input string
var output = input.replace(/'s/g,'');

更新后

您的代码看起来更像是希望用单个空间替换一个空间的多个实例,这仍然可以通过与原始表达式略有不同的表达式来完成:

// This replaces multiple repeated instances of a space with a single
var trimmedName = name.replace(/'s+/g,' ');
Index("default", trimmedName);

trim()函数将只删除字符串的前导和尾部空白,而不会删除字符串单词之间的空格

是否确保在trim()之后重新分配变量?

var test = "   Hello World   ";
test = test.trim(); // "Hello World"