Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RexExp How to stop with `n` time on replace string

Here is my string:

const str = "abc def ghi jkl";

I am looking for a result as : abcdefghi jkl first 2 space removed. But at present with my pattern I could not able to extend to 2 times. it only takes the first space and replaces.

my patten:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const letters = str.replace(/([^a-zA-Z])/,  '',);

How to replace only the required times of space replaced?

my result at present: abcdef ghi jkl

for additional knowledge to learn, how to replace only the last or only the 2 instance from the last as well?

>Solution :

Do not let RegEx take away your modesty, a simple for-loop will suffice:

const str = "abc def ghi jkl";
let letters = str;
for (let i = 0; i < 2; i++) {
  letters = letters.replace(/([^a-zA-Z])/,  '',);
}

console.log(letters)

Regarding your side question, if you need to do the last, then match the RegEx from the back by adding a greedy match group in the front .*, then replace the string with that greedy match group:

const str = "abc def ghi jkl";
let letters = str;
for (let i = 0; i < 2; i++) {
  letters = letters.replace(/(.*)[^a-zA-Z]/, '$1',);
}

console.log(letters)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading