我试图使用javascript中的正则表达式在字符串前后删除空格。一种解决方案是将所有空白替换为零。我想出了一个不同的解决方案,在字符串前后匹配所有非空格字符(我在单词之间匹配了1个空格)。由于某些原因,它不起作用,结果仍然包括空格。任何帮助都将不胜感激!
let hello = " Hello, World! ";
let wsRegex = /(?<=\s*)\S*\s\S*/g; // Change this line
let result = hello.match(wsRegex); // Change this line
console.log(result);
发布于 2022-08-07 05:56:47
您可以使用命名组来获取字符串,而不需要启动和尾随空格。
下面是一个修改代码的示例:
let hello = " Hello, World! ";
let wsRegex = /^\s*(?<hello>.+\S)\s*$/m; // Change this line
let result = hello.match(wsRegex)?.groups?.hello; // Change this line
console.log(result);发布于 2022-08-07 05:15:03
请使用String#replace:
var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");如果使用匹配
let result = hello.match(/\S+/g); https://stackoverflow.com/questions/73265048
复制相似问题