gpt4 book ai didi

javascript - 正则表达式删除空格

转载 作者:行者123 更新时间:2023-11-28 20:29:13 25 4
gpt4 key购买 nike

我正在尝试编写一个正则表达式来删除单词开头的空格,而不是后面的空格,并且仅删除单词后面的一个空格。

这是我尝试过的正则表达式:

var re = new RegExp(/^([a-zA-Z0-9]+\s?)*$/);
Output -
re.test("")
true - required false
re.test(" ")
false
re.test(" word")
false - required word - true
re.test(" word ")
false - required word - true
re.test("word ")
true
re.test("word ")
false - - required word(with single space ) - true

经验:

看,我必须向后端发送请求,如果

1) key term is ""(blank) no need to send the request. 
2) If key is " string" need to send the request.
3) If user enter something like this "string string" need to send the request.
4) if user enter "string " need to send the request.
5) if user enter string with a space need to send the request but at the moment he enter another space no need to send the request.

这件事我试图使用正则表达式来实现。

最佳答案

我认为以下应该为您处理所有空间替换:

var str      = "   this is     my  string    ";
var replaced = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// repl = 'this is my string'

关于javascript - 正则表达式删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16736950/

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