0

I have an input control, user can enter only numeric values or hyphen. When everything is done, I should transform entered value from input into a valid fips code (it looks like 'xx-xxx'). What is the most efficient way to do that? From the first sight it seems basic for loop can do that. Are there more advanced ways like RegEx for this kind of transformations? Thanks!

const someUserInputValueBeforeOnBlur = '12313213-12312313'
let newString = ''

for (let i = 0; i < string.length; i++) {
    if (i === 2) {
        newString += '-'
    }
    if (i === 5) {
       break
    }
      newString += string[i] 
} //expected output of newString: 12-313
s_kamianiok
  • 365
  • 2
  • 13
  • 1
    Looks like you are looking to create a regex, but do not know where to get started. Please check [Reference - What does this regex mean](https://stackoverflow.com/questions/22937618) resource, it has plenty of hints. Also, refer to [Learning Regular Expressions](https://stackoverflow.com/questions/4736) post for some basic regex info. Once you get some expression ready and still have issues with the solution, please edit the question with the latest details and we'll be glad to help you fix the problem. – Wiktor Stribiżew Mar 19 '20 at 11:53
  • Using substring: `str.substring(0, 2) +'-' +str.substring(2, 5)` – Nick Parsons Mar 19 '20 at 11:57

0 Answers0