Add space to the 3rd character from the end of the line

I am using Angular JS and I am doing validation for postal code in the UK. The problem is that there is a specific requirement that the UK postal code must indicate a space that can only be identified by counting the characters from the latter. Since there should be a space before the third last character, it should look like this:

A12 3AD
A123 3AD
A2 2AD

For this, I have two main problems:

  • How to manipulate an input value to invoke space.

  • How to change line to add space

I'm new to javascript/angularcan someone tell me how to do this?

PS: I do not use jQuery in the project.

+4
5

String#replace 3 , .

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}$)/, ' ')
)
Hide result

String#split Array#join .

string = string.split(/(?=.{3}$)/).join(' ');

console.log(
  'A123A123'.split(/(?=.{3}$)/).join(' ')
)
Hide result
+5

.

string = string.replace(/.{3}$/,' $&');

, : , 3-

+2

, ; , , title, placeholder, required :invalid css, pattern, RegExp ^[A-Za-z0-9]{2,4}\s[A-Za-z0-9]{3}$.

input[type="text"] {
  width: 200px;
}

input:invalid {
  color:red;
  font-weight: bold;
}
<input type="text" 
       title="Input three alphanumeric characters, a space, followed by three alphanumeric characters. All other input is invalid."
       placeholder="Input valid UK postal code."
       pattern="^[A-Za-z0-9]{2,4}\s[A-Za-z0-9]{3}$"
       required/>
Hide result
+1

,

Use the method spliceto split a string into two parts. string.length-3will contain the last three characters, where it string.slice(0, string.length-3)will return the first characters n-3, starting from the beginning of the line. Use the array.joinmethod to combine fragments.

function insertSpace(string){
var output = [string.slice(0, string.length-3),' ', string.slice(string.length-3)].join('');
return output
}
console.log(insertSpace('A1233AD'))

Demo

0
source

You can also use the substring function:

str.substring (0, str.length - 3) + "" + str.substring (str.length, str.length - 3)

-1
source

Source: https://habr.com/ru/post/1664127/


All Articles