Regex phone masking - javascript

I'm trying to write phone input masking function. Here it is:
let input = document.querySelector('input');
input.addEventListener('input', ()=>{
let x = event.target.value.replace(/\D/g, '').match(/(\d{0,1})(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/);
event.target.value = !x[2] ? x[1] : '+' + x[1] + ' (' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '') + (x[5] ? '-' + x[5] : '');
})
<input />
It works, but with one problem. When I press the backspace key, I erase the phone number to something like +1 (111). Such an entry is valid for the regular expression, and the string is replaced by itself

Per #ggorlen's suggestion in the comments, here is one way to do this:
let input = document.querySelector('input');
input.addEventListener('keydown', (event)=>{
if (event.key === "Backspace" || event.key === "Delete") return;
let x = event.target.value.replace(/\D/g, '').match(/(\d{0,1})(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/);
event.target.value = !x[2] ? x[1] : '+' + x[1] + ' (' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '') + (x[5] ? '-' + x[5] : '');
})
<input maxlength=18 />

Related

How to run form input phone mask on load?

I am masking a phone input via typing like this:
<script type="text/javascript">
document.getElementById("phoneinput_<%= dom_id(field) %>").addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
</script>
When I am editing the form and the phone field values are pulled from the DB I also need to format them on load outside of the input event listener. How do you do this?
Do a .dispatchEvent(new Event("input")) to trigger an input:
let elem = document.getElementById("phoneinput");
elem.addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
elem.dispatchEvent(new Event("input"));
<input id="phoneinput" value="1234567890" />

Phone number input mask in JS

I'm trying to figure out where the number 1 comes from (in the example below you write any phone number and press Backspace many times). Can you please tell me what is wrong in this code?
const input = document.querySelector('input[name="phone"]');
input.addEventListener('input', function () {
let x = input.value;
x = x.replace(/^\+1 /, '');
x = x.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/);
x = !x[2] ? x[1] : x[1] + ' ' + x[2] + (x[3] ? `-${x[3]}` : '') + (x[4] ? `-${x[4]}` : '');
x = x.startsWith('+1 ') ? x : '+1 ' + x;
input.value = x;
});
<input name="phone" placeholder="Phone number">
You need remove it on your code.
phone = phone.replace(/^\+1 /, '')
Also:
phone = phone.startsWith('+1 ') ? phone : '+1 ' + phone;
You had to replace the line:
x = x.replace(/^\+1 /, '');
to:
x = x.replace(/^\+1/, '');
(remove the space)

Autoformat input field

I have a javascript, which I supposed to format phone number to +1 (222) 555 22-22, but for some reason it stops to work just on first number.. Can you elaborate what's I'm doing wrong?
document.getElementById('phone').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,1})(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[3] ? x[1] : '+' + x[1] + '(' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '');
});
<input type="text" id="phone" placeholder="+1 (222) 444-5555"/>

How do you put the last character 1st in a string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The R is displaying last in the string initially it must display first how can I put the last character before the number value in the string so that it can display at the beginning of the value
contentHtml +=
"<td rowspan1=\"" + 1 + "\" class=\"" + (rowspan !== "" && rowspan > 1 ? "groups" : "") + " " + (!isNaN(value) || (!isNaN(value.toString().substr(1, value.length)) || value == "N/A" || value.length < 7 && value.toString().substr(value.length - 1) == '%') ? "text-center" : "text-left") + "\">" + value + (!isNaN(value) ? preFix : "") + color + (!isNaN(value) ? postFix : "") + "</td>";
if (rowspan > 1) {
var rowspanContent = "<td rowspa1=\"" + rowspan + "\" class=\"" + (rowspan !== "" && rowspan > 1 ? "groups" : "") + " " + (!isNaN(value) || (!isNaN(value.toString().substr(1, value.length)) || value == "N/A" || value.length < 7 && value.toString().substr(value.length - 1) == '%') ? "text-center" : "text-left") + "\">" + value + (!isNaN(value) ? preFix : "") + color + (!isNaN(value) ? postFix : "") + "</td>";
}
If you want o swap the numbers and letters you should see Nina Scholz answer.
If you just want to put the last character first you can do it like this:
function lastToFirst(value){
return value.slice(-1) + value.substring(0,value.length-1);
}
or even cleaner
function lastToFirst(value){
return value.slice(-1) + value.slice(0,-1);
}
You could use a regular expression and swap numbers and letters (not numbers).
function swap(s) {
var m = s.match(/^(\d+)(\D+)$/);
return m[2] + m[1];
}
console.log(swap('1234R'));
Otherwise, you could change your code from
value + (!isNaN(value) ? preFix : "") + color + (!isNaN(value) ? postFix : "")
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
to
(!isNaN(value) ? preFix : "") + value + color + (!isNaN(value) ? postFix : "")
//^^^^^^^^^^^^^^^^^^^^^^^^^^^
and use preFix instead of postFix.
Direct answer is:
var value ="1234567R";
var res = "R" + value.split("R")[0];
alert(res);
Without code, it's compicated to help.
If just you want to put the last x chars to first, here is a little piece of code
var nb = 1;
var s = "123456789R";
var last = s.split(s[s.length - (nb - 1)])[1];
var s1 = s.slice(0, s.length - nb);
s = last + s1;
//s => "R123456789"

Sort based on string "weight"

I searched on the internet for a sort algorithm which sorts the entries of a table in a "natural" way so 10 is after 1 and so on but I found not one solution which is "the perfect fit".
Now I am working on my own solution to do a sort algorithm. My question is now if it is efficient and applicable to create a number for each string in a table row based on the position of their letters in the abc and the position of this letter in the specific string and then sort by this created number?
Example:
abc would be a = 1; b = 2; c= 3 and then the "weight" for each letter should be higher with the string length:
a = 1 * 1(pos in str); b = 2 * 2; c = 3 * 3
so abc would be 14 as a number.
I don't want this to be a real natural sort.
I have used libraries and the built in Javascript function ".sort()" but they are not working for strings like 92593c17-5183-4db1-b4bd-d538abb4124bor ed06d686-8a04-4ae1-9500-975fb85a49d9 so it is not the right thing for me.
So is it a good way to sort strings by their letter-"weight"?
Have a look at this little example with localeCompate():
var s1 = '92593c17-5183-4db1-b4bd-d538abb4124';
var s2 = 'ed06d686-8a04-4ae1-9500-975fb85a49d9';
var s3 = '10';
var s4 = '1';
var s5 = 'a';
var s6 = 4;
$('#1').text(s1 + ' before ' + s2 + ': ' + (s1.toString().localeCompare(s2.toString()) == -1 ? 'yes' : 'no'));
$('#2').text(s2 + ' before ' + s3 + ': ' + (s2.toString().localeCompare(s3.toString()) == -1 ? 'yes' : 'no'));
$('#3').text(s3 + ' before ' + s4 + ': ' + (s3.toString().localeCompare(s4.toString()) == -1 ? 'yes' : 'no'));
$('#4').text(s4 + ' before ' + s5 + ': ' + (s4.toString().localeCompare(s5.toString()) == -1 ? 'yes' : 'no'));
$('#5').text(s5 + ' before ' + s6 + ': ' + (s5.toString().localeCompare(s6.toString()) == -1 ? 'yes' : 'no'));
$('#6').text(s6 + ' before ' + s1 + ': ' + (s6.toString().localeCompare(s1.toString()) == -1 ? 'yes' : 'no'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='1'></p>
<p id='2'></p>
<p id='3'></p>
<p id='4'></p>
<p id='5'></p>
<p id='6'></p>

Categories