ssp singh
ssp singh

Reputation: 152

Once replaced, skip that part of string - Regex Javascript

I expect a string of just numbers from HTML inputbox but i am looking for a regex so that i can capture some part of string and replace it with something and now what i want is, for next iteration, regex should skip part which has been processed.

Take a look at my regex

string.replace(/([\d]{10})/gm, "$1,")

Expected results for iterations

  1. 895645784578457845784578457845 source
  2. 8956457845,7845784578,4578457845,9089 more data is coming

But problem is result

  1. 8956457845,7845784578,4578457845
  2. 8956457845,,,7845784578,,,4578457845,,,9089

Upvotes: 0

Views: 80

Answers (1)

Sphinx
Sphinx

Reputation: 10729

If I understood correctly, you'd like to apply regex-replace for one numerical string recursely like string.replace(\regex\, '$1,').replace(\regex\, '$1,').replace(\regex\, '$1,'), but ignored the parts which already replaced.

Below is one solution which uses negative lookahead.

let test = '895645784578457845784578457845' //org string
let test1 = test.replace(/(\d{10}(?!\,))/gm, "$1,")
                .replace(/(\d{10}(?!\,))/gm, "$1,")
                .replace(/(\d{10}(?!\,))/gm, "$1,") 
                // simulate recurse-replace three times
console.log(test1)

test1 += '1234567890123' //new string came
let test2 = test1.replace(/(\d{10}(?!\,))/gm, "$1,")
console.log(test2)

test2 += '1234567890123' //new string came
let test3 = test2.replace(/(\d{10}(?!\,))/gm, "$1,")
console.log(test3)

Upvotes: 3

Related Questions