JavaScript - 正则表达式删除括号内的空格,单引号内的空格除外

时间:2021-07-22 03:51:41

标签: javascript regex

我需要您的帮助,使用 regex 中的替换方法中的 JavaScript 删除括号内的空格,但单引号内的空格除外。

Input - substringof('John', name) eq true
Output - substringof('John',name) eq true

Input - substringof('John' ,name) eq true
Output - substringof('John',name) eq true

Input - substringof('John ' , name) eq true
Output - substringof('John ',name) eq true

我尝试了一些 regex,但无法获得所需的东西。

2 个答案:

答案 0 :(得分:0)

使用单个 RegEx 可能无法做到这一点。

您可以尝试提取要从中删除空格的字符串部分:

\((.*?)'.*'.*?\)

这将捕获第一个捕获组中左括号和左单引号之间的字符,以及第二个捕获组中右括号和右单引号之间的字符。

在这里试试:https://regex101.com/r/q1krmG/1/

您可以从字符串的这些部分轻松删除空格。

答案 1 :(得分:0)

使用 replacerFunction

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

const input = "substringof( 'John ' , name ) eq true"

const output = input.replace(/\((.*),(.*)\)/, (m, p1, p2) => `(${p1.trim()},${p2.trim()})`)

console.log(output)

单独使用 regex

https://regex101.com/r/oroU4l/1

const input = "substringof( 'John ' , name ) eq true"

const output = input.replace(/\(\s*(.*?)\s*,\s*(.*?)\s*\)/, '($1,$2)')

console.log(output)