Lokesh Yadav
Lokesh Yadav

Reputation: 1602

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 helpful.

Upvotes: 1

Views: 2668

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173642

You could 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"

Upvotes: 1

domyos
domyos

Reputation: 21

As you first five characters are numbers you can catch those in a capture group. Check if those are followed by (-) or (_) and replace those.

You would do this with the following regex:

str.replace(/(\d{5})[\-_](.*)/, '$1$2');

First you create a capture group to save the first five digits (\d{5}). Then you look for the characters you want to delete [\-_]. After that you capture the rest of your string (.*).

Now you can replace your string with the to capture groups '$1$2' and you are done.

Upvotes: 2

Related Questions