0

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
3
  • 1
    Works for me. "895645784578457845784578457845".replace(/([\d]{10})/gm, "$1,") returns "8956457845,7845784578,4578457845," as one would expect. Commented Sep 4, 2018 at 16:51
  • 2
    Side note: [\d] is just a long way to write \d. :-) Commented Sep 4, 2018 at 16:52
  • probably you;d like to use negative lookahead /(\d{10}(?!\,))/gm, like this fiddle Commented Sep 4, 2018 at 17:06

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.