使用单个正则表达式

时间:2017-09-12 21:17:15

标签: javascript regex

标题说明了一切

  • 单一正则表达式
  • 删除前导空格
  • 删除尾随空格

"  fooHello World" => "Hello World"
"fooBing space in the middlefoo  " => "Bing space in the middle"
"  foo " => ""
" fooHellofoo  " => "Hello"

2 个答案:

答案 0 :(得分:0)

您可以使用trim()删除前导/尾随空格。

您可以使用replace()通过正则表达式定位foo并将其删除。尝试运行以下代码段:



const trimAndRemoveFoo = (str) => {
  return str.trim().replace(/foo/g, '');
}

// log trimAndRemoveFoo function with sample strings
console.log(trimAndRemoveFoo("  fooHello World"));
console.log(trimAndRemoveFoo("fooBing space in the middlefoo  "));
console.log(trimAndRemoveFoo("  foo "));
console.log(trimAndRemoveFoo(" fooHellofoo  "));




答案 1 :(得分:-1)

您可以使用replace进行正则表达式搜索,并使用以下正则表达式/\W*foo\W*/g



const strs = [
  "  fooHello World",
  "fooBing space in the middlefoo  ",
  "  foo ",
  " fooHellofoo  "
];

const results = strs.map((str) => {
  return str.replace(/\W*foo\W*/g, '');
});

console.log(results)