在JavaScript中提取两个特殊字符之间的字符

知识管理

说我有一个字符串

MyLongString %StringIWant% withe the %getanother%

我想提取位于%字符之间的字符串。这意味着我需要从该字符串中获取“ StringIWant”和“ getanother”。用JavaScript可以做到这一点吗?

彼得·塞利格

使用正则表达式,例如/%([^%]+)%/g...

  • 匹配一个%字符,
  • 然后捕获所有不是%字符的东西,
  • 然后再匹配一个(终止)%字符...

const sample = `
  MyLongString %StringIWant% withe the %getanother% foo bar
  MyLongString %StringIWant% withe the %getanother% %wanted%
  %wanted% %StringIWant% withe the %getanother% foo %wanted%`;

console.log(
  Array
    .from(sample.matchAll(/%([^%]+)%/g))
    .map(([match, capture]) => capture)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章