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