gpt4 book ai didi

javascript - 如何使用javascript trim 单词之间和逗号后的空格

转载 作者:搜寻专家 更新时间:2023-11-01 04:53:25 24 4
gpt4 key购买 nike

我有以下名为 name 的字符串,我想 trim 句子中单词之间的空格以及逗号后的空格。我可以在句子的开头和结尾使用 trim() 来 trim 多余的空格。
[我正在使用 javascript 来实现我的代码]

name = '      Barack Hussein       Obama II is an     American politician who served       as the 44th President        of the United States from January 20,    2009,    to January 20, 2017.  

预期输出:

name = ' Barack Hussein  Obama II is an American politician who served  as the 44th President of the United States from January 20, 2009, to January 20, 2017. 

最佳答案

假设剩下的双空格只是一个拼写错误,您可以使用正则表达式匹配一个或多个空格,并用一个空格替换每个空格:

const name1 = '      Barack Hussein       Obama II is an     American politician who served       as the 44th President        of the United States from January 20,    2009,    to January 20, 2017.';
console.log(
name1.replace(/ +/g, ' ')
);

关于javascript - 如何使用javascript trim 单词之间和逗号后的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52383437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com