hi i have one input type tel for mobile number and like use pattern for number format like this
938 119 1229
but when i use type tel i can use word in input
i try use the two regex in one input but i don't know how :
function mobileNumInput(input){
var regex = /[^0-9]/g; //for digit only
input.value=input.value.replace(/^(\d{3})(\d{3})(\d+)/, '$1 $2 $3'); //for space between numbers
input.value=input.value.replace(regex)
}
and html :
<input type="tel" name="phone" placeholder="912 000 0000" maxlength="12" min="0" max="9" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" onkeyup="mobileNumInput(this)" autofocus>
this is my placeholder:
enter image description here
i want this format :
enter image description here
But I don't want to use word like this :
enter image description here
sorry my english is bad
I'm guessing that you want to do the following:
Remove all non-numeric characters from the phone number.
Example: convert '(111)-174-1234' to '1111741234'
Add spaces in the correct location to the resultant number.
Example: convert '1111741234' to '111 174 1234'
If my assumptions about the purpose of this code are true, your code had two mistakes:
You put step #1 after step #2.
This led to an input '(111)-174-1234' having the regex (#2) running the following replacement: .replace(/^(\d{3})(\d{3})(\d+)/, '$1 $2 $3')
The above snippet of code only works on pure numbers. It does not recognize '(111)-174-1234' as containing any matches to /^(\d{3})(\d{3})(\d+)/, so no replacements are made. In other words, after line 3 of your code runs, input.value has likely not changed.
The solution to this is simply to switch line 3 and 4 in your program.
In step #1, you used .replace(regex) instead of .replace(regex,'').
This is just a String method technicality: String.prototype.replace accepts a regex and a string to replace it. Leaving the second parameter empty is the same as setting the second parameter as undefined.
An example is that "Hello world".replace(/l/g) is the same as "Hello world".replace(/l/g,undefined). The result of both of these snippets is "Heundefinedundefinedo world". You can gain the desired behavior by using "Hello world".replace(/l/g,'') instead. This will return "Heo world".
I put my fixes into a revised version of your code:
function mobileNumInput(input){
var regex = /[^0-9]/g; //for digit only
input.value=input.value.replace(regex, ''); // Step #1 (remove non-digits)
input.value=input.value.replace(/^(\d{3})(\d{3})(\d+)/, '$1 $2 $3'); //Step #2 (add spaces to valid phone number)
}
Here is a slightly further modified version of your code with one test:
function mobileNumInput(input){
input.value=input.value
.replace(/[^0-9]/g, '')//Remove all non-digits
.replace(/^(\d{3})(\d{3})(\d+)/, '$1 $2 $3'); //Add spaces to the only-digit number
}
function test(){
var testInputElement=document.createElement("input");
testInputElement.value='(123)-[456} - 7890';//Horribly formatted phone number
mobileNumInput(testInputElement);
console.log(testInputElement.value);
}
test();
//123 456 7890
Related
I'm trying to replace some words in a string with .replace(desiredWord,""), to remove those words from that string.
I have a string which is like this "xsmall small medium" and I'm trying to remove "small" from that string in some events, but it sometimes removes small of xsmall also, which is not my intention..
Is there any way to restrict replace method or I should use another method?
I want to replace or remove specific word, not letters.
The following should work:
If you pad your desiredWord with the word boundary \b operator it will work without false positives.
const sampleString = "xsmall small medium";
console.log(sampleString.replace(/\bsmall\b/g, "test"));
With variable
document.querySelector("#replace").addEventListener("click", (e) => {
debugger
const value = document.querySelector("#change").value;
//escape the operators in the regexp!
const regex = new RegExp("\\b"+value+"\\b", "g");
document.querySelector("#text").value = document.querySelector("#text").value.replace(regex, "test");
}, true);
<input readonly id="text" value="xsmall small medium" /><br />
<input id="change"><button id="replace">Replace</button>
You can use a RegEx expression for this.
You can use these in the replace method directly.
A way to check this is using the next expression: \bsmall
The result of this is as follow :
string.replace(\bsmall, "")
\b will check if the characters are from 1 and only 1 word
You could exclude letters before explicitly:
const sampleString = "xsmall small medium";
console.log(sampleString.replace(/([^a-z])(?=small)/ig, "$1x");
This regular expression reads, "Not a letter, followed by (but not captured) 'small', replaced with whatever the non-letter was, followed by an x."
or the same thing using the word boundary feature, just be sure not to delete it too:
const sampleString = "xsmall small medium";
console.log(sampleString.replace(/(\b)(?=small)/ig, "$1x");
This one reads, "Any word boundary, followed by 'small' (but without 'small' forming part of the replacement), replaced by the word boundary and then an 'x'.
I'm trying to auto format an input on HTML with javascript, and it is almost done, i need the format to be xxx-xxx-xxxx but and I have this code
this.value = this.value.replace(/(\d{3})\-?/g,'$1-');
as youy can see it will just auto format xxx-xxx-xxx but I need to be 4 digits at the end
any sugestions?
Try this regexp:
'1234567890'.replace(/(\d{3}(?!\d?$))\-?/g, '$1-'); // 123-456-7890
The part (?!\d?$) is a negative lookahead. It allows regular expression to match three digits only if they are not followed by another number (4th) (but not necessarily ?) at the end of the string $.
So it will not match 789 group because it's followed by 0$.
Or simply : .replace(/(\d{3})(\d{3})(\d{4})\-?/g,'$1-$2-$3');
Sample code to help you out:
var phone = '(555) 666-7777';
// First clean your input
phone = phone.replace(/[^\d]/g, '');
// Check the length of the phone
if(phone.length == 10){
// Now we can format the phone
phone = phone.substring(0,3)+'-'+phone.substring(3,6)+'-'+phone.substring(6, 10);
// Optionally
//phone = phone.replace(/(\d{3})(\d{3})/, '$1-$2-');
}
else {
// whatever you want to tell the user
}
there seems to be a bug in the "replace" regex's above. enter a 10 digit number and you see it formatted correctly (e.g. "(123) 456-7890"). Then, select the contents of the field (double or triple click it) and overtype the value. You'll see the first two digits get transposed. So if you enter 1 2 3, you'll see 2 1 3...
I have inputs with names:
<input type="text" name="data[Site][search]">
<input type="text" name="data[Site][name]">
I want to get when I click only:
search
name
etc.
My JS in click event
var reg = /data\[Site\]\[\d\]/g;
var test = $(this).attr("name").match(reg);
console.log(test);
But console display null. What is wrong in my reg?
Try with using this:
var reg = /data\[Site\]\[(.+)\]/g; //Capture the characters between []
var test = reg.exec($(this).attr("name"));
console.log(test[1]); //Output search | name
Demo
You're using \d which means digits only, you're also not specifying a quantifier so you'll only capture one digit at most, i.e:
data[Search][1]
You could use \S which is any non-whitespace character. You want to do this for at least one character (as you shouldn't have data[Search][] and you'll also want to capture the name, so throw in some (). You could switch \S to specific characters using character sets, for example [A-Za-z0-9].
Anyhow, your modified example should not look something like this:
var reg = /data\[Site\]\[(\S+)\]/g;
var test = $(this).attr("name").match(reg);
console.log(test);
You'll be able to pull the actual value from the match captures using test[1].
I am not sure why this regex expression is not working.
I want to validate if the input is in this format : 12345678,12345678,12345678*space*12345678 , 12345678 , 12345678 , 12345678 12345678,12345678, space
It must be 8 digit if not return false.
Below is the regex expression that i did, But it is working for 2 sets of numbers but when i input another set of numbers validation is not working.
Working: 12345678 , 12345678
Not Working: 12345678 , 12345678 ,12345678
var validate_numbers = /^\s*\d{8}\s*\+*(,\s*\d{8},*)?$/;
Thank you
You need to describe what you want to match in more detail. I'm going to assume you want to match 8-digit nums delimited by commas and pluses, possibly followed by commas.
The problem is you're taking at most 2 sets of digits. Visualization.
Given the assumption above, this is the regex you want:
^(\s*\d{8}\s*[+,]?\s*)*$
Again, you can visualize it on debuggex.
Could you give a little bit more detail about the requirement? Do you need to have a space before comma?
\\d{8}(?:,\\d{8})*+
Try with it. it works fine with requirement that validates a list of numbers, which have 8 digits, and separated by comma.
Hope it will helps
Remove the '$' from your current regular expression. It is strictly matching for the end of the line, which is causing your expression to return false on your desired strings. The following code returns TRUE for the strings that you mentioned which were previously returning FALSE.
omgerd I automatically wrote first response in PHP, here is quick JS edit
var pattern = /^\s*\d{8}\s*\+*(,\s*\d{8},*)?/;
var data2 = '12345678 , 12345678 ,12345678';
if (pattern.test(data2) != 0) {
alert("ok");
}
Output:
ok
I have a text box and it says "Phone:" as the standard here for phone number is (XXX)-XXX-XXXX
I'd like to have a javascript that automatically puts my numbers into that format if it's not in that format, so if you typed 9993334444 then it would change it automatically on the fly as I'm typing to (999)-333-4444 I have looked around Google for Javascript Phone Regex to no success, maybe a Regex isn't what I'm looking for?
you want to add an onkeyup event with a regex like
this.value = this.value.replace(/^\(?([0-9][0-9][0-9]){1}\)?-?([0-9][0-9][0-9][0-9]){1}-?([0-9][0-9][0-9]){1}$/, '($1)-$2-$3');
Check out http://jsfiddle.net/R8enX/
/ means start/end a regex string
^ means start of matching string
$ means end of matching string
? means 0 or 1 instances (make braces and dashes optional)
[0-9] means any single digit
(x){1} tags x as an expression that we can reference in the replacement with a $ sign
EDIT: realized I missed a digit on the last group of numbers, the jsfiddle will only work (properly) with 3 digits in the last group
To build somewhat on #Andrews answer you can check for a valid (local)phone number via this method. If the number is shorter or larger than 10 digits, it collapses back into an invalid number
-
<input type="text" onBlur="localNumber(this.value)"/>
<div id="output"></div>
-
<script>
var localNumber = function(str){
repl = str.replace(/^([0-9]{3})([0-9]{3})([0-9]{4})$/, "($1)-$2-$3");
outp = document.getElementById('output');
if( repl.match(/\W/) )
{
outp.innerHTML = repl;
}
else
{
outp.innerHTML = 'Invalid number for this region';
}
}
</script>