简体   繁体   English

替换特定字符前后的空格 - Javascript

[英]Replace space before and after a particular character - Javascript

Is there a way to replace space before and after a particular character in Javascript?有没有办法替换 Javascript 中特定字符前后的空格?

Scenario: string - "( 'fever' ) OR ( 'cold' )"场景:字符串 - “(‘发烧’)或(‘感冒’)”

I just want to remove spaces before and after single quotes我只想删除单引号前后的空格

expected result - "('fever') OR ('cold')"预期结果 - “('发烧')或('感冒')”

Thanks In Advance提前致谢

You can use a regex:您可以使用正则表达式:

 const s = "( 'fever' ) OR ( 'cold' )" const out = s.replace(/(?:\s+('\w+')\s+)/g, '$1') console.log(out)

The question is tagged regex, but sometimes I would just do something like this:这个问题被标记为正则表达式,但有时我会做这样的事情:

function replaceAll(before, after, string) {
  let result = string;
  while (result.indexOf(before) !== -1) {
    result = result.replace(before, after);
  }
  return result;
}
let example = "( 'fever' ) OR ( 'cold' )";
example = replaceAll("' ", "'", example);
example = replaceAll(" '", "'", example);
console.log(example);

You can use lookaround like this:您可以像这样使用环视:

 const s = "( 'fever' ) OR ( 'cold' )" const out = s.replace(/(?<=\()\s+|\s+(?=\))/g, '') console.log(out)

Where:在哪里:

  • (?<=\()\s+ matches 1 or more spaces preceded by an opening parenthese (?<=\()\s+匹配前面有一个左括号的 1 个或多个空格
  • \s+(?=\)) matches 1 or more spaces followed by a closing parenthese \s+(?=\))匹配 1 个或多个空格后跟右括号

You can also use this:你也可以使用这个:

 const s = "( 'fever' ) OR ( 'cold' )" const out = s.replace(/(?<=')\s+|\s+(?=')/g, '') console.log(out)

Where:在哪里:

  • (?<=')\s+ matches 1 or more spaces preceded by a single quote (?<=')\s+匹配 1 个或多个空格,前面有一个单引号
  • \s+(?=') matches 1 or more spaces followed by a single quote \s+(?=')匹配 1 个或多个空格后跟单引号

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

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