Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a space before 3rd character from end of string

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:

  1. How to manipulate input value to induce space.

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

like image 904
vaibhav Avatar asked Dec 19 '16 05:12

vaibhav


1 Answers

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(' ')
)
like image 167
Pranav C Balan Avatar answered Sep 21 '22 01:09

Pranav C Balan