Skip to content Skip to sidebar Skip to footer

Use Match In Replace

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 th

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

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

Solution 3:


Post a Comment for "Use Match In Replace"