在替换中使用匹配 [英] Use match in replace

查看:13
本文介绍了在替换中使用匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将每个非字母字符放在空格之间.我想使用 RegExp 执行此操作,并且我理解将它们全部选中 (/(^a-zA-Z )/g 就足够了.
有没有办法在替换中使用原始匹配?(就像是)str.replace(/(^a-zA-Z )/g,/\m/);如果不是,我将遍历所有这些,但我真的想知道这是可能的.

I need to put every non-alphabetic character between spaces. I want to do this using RegExp, and I understand it enouch to select them all (/(^a-zA-Z )/g).
Is there a way to use the original match inside the replace? (something like) str.replace(/(^a-zA-Z )/g,/ \m /); If not I will just loop over all of them, but I really want to know it it is possible.

推荐答案

是的.您可以在搜索时为 String.prototype.replace() 函数提供一个 RegExp.你也可以给它一个处理替换的函数.

Yes. You can give the String.prototype.replace() function a RegExp as it's search. You can also give it a function to handle replacing.

该函数会给你匹配作为第一个参数,然后你返回你想要改变它的内容.

The function will give you the match as the first parameter, and you return what you want to change it to.

const original = 'a1b2c';
const replaced = original.replace(/([^a-z])/gi, match => ` ${match} `);
console.log(replaced);

如果你只需要做一些简单的事情,你也可以只使用 $n 值($1$2 等)来根据选定的组(括号集)替换.

If you just need to do something simple, you can also just use the $n values ($1, $2, etc) to replace based on the selected group (the sets of parentheses).

const original = 'a1b2c';
const replaced = original.replace(/([^a-z])/gi, ' $1 ');
console.log(replaced);

这篇关于在替换中使用匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆