Regular expression to remove certain characters after nth index value

We are working on a form validation code snippet where jQuery masking plugin has been used to enforce validation on user input.

Masking Pattern used with zip code field is 99999?-9999 where everything is optional after “?”.

Problem occurs when user fill up the form using autofill feature in chrome[i.e. double click on input field and select value] and submit the form. On form submission, zip code value is coming as 23455-____ which includes masking pattern characters as well i.e. hypen & underscore.

Refer attached screenshot after using autofill feature. http://inft.ly/3mmtNdA

If optional characters contains Hypen (-) and underscore(_) then those needs to be removed before submitting it to server. I am trying to use regex but didn’t find anything which checks for specific characters after 5th index item and then remove those.

Any help would be really appreciated.

You can use a global search for digits, which removes anything else that is not a digit.

'23455-____'.match(/\d/g) // ['2', '3', '4', '5', '5']

Or if you want the digits to be all joined together:

'23455-6789'.match(/\d/g).join(''); // '234556789'

@Paul_Wilkins Can’t use join as “-” is a must if zip code is filled with all 9 digits. Second, it is not always digits in zip code, there are few regions where zip code is alphanumeric. For ex. zip for canada is alphanumeric. So, i need to read masking pattern first to get the index of “?” then pass this index to regular expression to remove special characters after index value.

To overcome this combinations, i was searching for a regex pattern which returns string after 5th index value. For e.g. if string is “23345-_____” then that regex should search for “-” & “_” after 5th digit.

Do acceptable values always and only start with 5 digits?
If so you can specify like
[\d]{5}

Good regex is all about patterns, you need to recognize both what to include and what to exclude

Issue is resolved by simply strip the trailing underscores or dashes from the string like so:

var str = '12345-_____';
str.replace(/[-_]+$/, ''); // "12345"

var str = '12345-123__';
str.replace(/[-_]+$/, ''); // "12345-123"

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.