I am using Angular JS and I am doing the validation for UK postal code. Issue is there is a specific requirement that there should be an space in the the UK postal code which can be identified only by counting character from last.As there should be a space before third last character It should look like:
A12 3AD
A123 3AD
A2 2AD
For doing that I have 2 major issues:
How to manipulate input value to induce space.
How to actually change the string to add space
I am new to javascript/angular
can someone tell me how to do that?
PS: I am not using jQuery in project.
Use String#replace
method and replace last 3 characters with leading space or assert the position using positive look-ahead assertion and replace with a white space.
string = string.replace(/.{3}$/,' $&');
// or using positive look ahead assertion
string = string.replace(/(?=.{3}$)/,' ');
console.log(
'A123A123'.replace(/.{3}$/, ' $&'), '\n',
'A13A123'.replace(/.{3}$/, ' $&'), '\n',
'A1A123'.replace(/.{3}$/, ' $&'), '\n',
'AA123'.replace(/.{3}$/, ' $&'), '\n',
'A123'.replace(/.{3}$/, ' $&'), '\n',
'A123'.replace(/(?=.{3}$)/, ' ')
)
Or you can use String#split
and Array#join
method with positive look-ahead assertion regex.
string = string.split(/(?=.{3}$)/).join(' ');
console.log(
'A123A123'.split(/(?=.{3}$)/).join(' ')
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With