Use match in replace [duplicate]

依然范特西╮ 提交于 2020-01-05 04:08:14

问题


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.


回答1:


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);

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);



回答2:


Yes, it is possible. You can use regex with group:

var text = '2apples!?%$';
var nextText = text.replace(/([^a-zA-Z])/g, ' $1 ');

console.log(nextText); 



回答3:


You can check replace function on this link

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



来源:https://stackoverflow.com/questions/45087107/use-match-in-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!