Marius February 2016

How do I add white space in regex?

I have this code:

CODE JS:

const phone= /^\(?(\d{3})\)?[-]?(\d{3})[-]?(\d{4})$/;

After running this code has the following form

(123)132-1312

I want to add white space before the last parentheses as in the example below.

(123 )132-1312

Can you please tell me how to accept changes to the code so that white space?

Thanks in advance!

EDIT:

text = $(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "($1)$2-$3");
var testt=$(this).val().match(text);

I added this code to call here as add white space ...

Answers


Ram February 2016

This should work as you need:

/^\(?\s*(\d{3})\s*\)?[-]?(\d{3})[-]?(\d{4})$/


Fuujin February 2016

Depending on wether you always want the whitespace befor the closeing parenthesis or not your could go with:

^\(?(\d{3}\s?)\)?[-]?(\d{3})[-]?(\d{4})$

Background \s is for whitespaces. the ? stands for 0 or 1 occurrance of the previous sign. if you use + it is one or more and * is for 0 or more occurrences of the previous sign.

To test your regex you can always use regexpal

Post Status

Asked in February 2016
Viewed 3,083 times
Voted 8
Answered 2 times

Search




Leave an answer