Regex To Add A Space After The Fourth Chars Javascript
I have a string which is a car number plate. But for display purposes I what to add a space after the fourth char in this string. The data comes from a data service so I have to do
Solution 1:
Simple and clear way to do this, without regex:
var$regtext = $('#regNumber');
if ($regtext.length > 0)
{
var regtext = $regtext.text(),
newRegtext = regtext.substr(0, 4) + " " + regtext.substr(4);
console.log(newRegtext);
}
It's also pretty fast too: runs 10,000 times in 351ms, faster than splitting and joining etc. Good if you'll be processing loads of data from the webservice.
Solution 2:
You can use following jquery : Demo
$('.test').keyup(function() {
var foo = $(this).val().split(" ").join("");
if (foo.length > 0) {
foo = foo.match(newRegExp('.{1,4}', 'g')).join(" ");
}
$(this).val(foo);
});
Solution 3:
If you want to use regex the following should do it.
newRegtext = regtext.replace(/^(.{4})/,'$1 ')
Solution 4:
Try this code
$(document).ready(function(e) {
var$regtext = $('#regNumber');
var$regtext = $regtext.text();
if ($regtext.length > 0)
{
regCheck = /^([A-Z1-9a-z]{1,4})([A-Z1-9a-z]*)$/;
regtext = regCheck.test($regtext);
newRegtext = $regtext.replace(regCheck,"$1$2");
alert(newRegtext);
}
});
Post a Comment for "Regex To Add A Space After The Fourth Chars Javascript"