繁体   English   中英

Cloudant 中的 JS trim() 函数

[英]JS trim() function in cloudant

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

我怎样才能做到这一点?

更新:

我有一个 JSON 对象

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

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

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

当我查询时,系统显示:

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

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

PS:一个小问题,所以不需要全部解释。

根据定义, 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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM