var tel = "123457890";
if (tel.length != 10) {
console.log("Sorry, incorrect format.");
} else {
var areaCode = tel.substring(0,3);
var prefix = tel.substring(3,6);
var suffix = tel.substring(6,10);
console.log("(" + areaCode + ") " + prefix + "-" + suffix);
}
Everything about this works for me except I can't get it to check for digits only. When I troubleshoot it with suggestions and run it through http://repl.it/languages/JavaScript I run into error messages.
i.e. When I put a "w" in with a string of 10 numerical digits I want it to return "Sorry, incorrect format" as if I had put in the wrong amount of numbers, etc.
You can use regex:
var tel = "123457890";
if (!tel.match(/^\d{10}$/)) {
console.log("Sorry, incorrect format.");
} else {
var areaCode = tel.substring(0,3);
var prefix = tel.substring(3,6);
var suffix = tel.substring(6,10);
console.log("(" + areaCode + ") " + prefix + "-" + suffix);
}
Here's a fiddle:
http://jsfiddle.net/e1qq659g/
Here's a regex pattern:
http://regexr.com/3b77b
var regularExpression = /\d{10}/g;
(tel.match(regularExpression)) ? alert("All digits!") : alert("Not Digits!");
this will match the expression to the string in variable tel - if it does match it alerts "All Digits" - if it does not match it alerts "Not Digits!"
This works. It deletes all letters and checks if the length changes
var tel = "1234567890";
if (tel.length !== 10 || tel.length !== parseInt(tel).toString().length) {
document.write("Sorry, incorrect format.");
} else {
var areaCode = tel.substring(0,3);
var prefix = tel.substring(3,6);
var suffix = tel.substring(6,10);
document.write("(" + areaCode + ") " + prefix + "-" + suffix);
}
You can use RegExp both to check if it only contains digits and to extract each part:
var tel = document.getElementById("tel");
var result = document.getElementById("result");
tel.oninput = function(e){
//var match = tel.value.match(/^(\d{3})(\d{3})(\d{4})$/); // Basic RegExp
var match = tel.value
.replace(/\s/g, '') // Removing spaces before RegExp makes it simplier
.match(/^(\d{3}|\(\d{3}\))(\d{3})\-?(\d{4})$/);
if(match == null) {
result.innerHTML = "Sorry, incorrect format.";
return false;
}
// parseInt is optional
var areaCode = parseInt(match[1].replace(/[\(\)]/g,'')); // Just need this with the second RegExp
var prefix = parseInt(match[2]);
var subfix = parseInt(match[3]);
result.innerHTML = "Valida input: (" + areaCode + ") " + prefix + "-" + subfix + "\n"
+ "\n\tArea Code: " + areaCode
+ "\n\tPrefix: " + prefix
+ "\n\tSubfix: " + subfix
};
<input type="text" id="tel" placeholder="Enter a valid phone number"/>
<pre id="result"></pre>
This way you could change the RegExp to make that match a formatted input too, lets say (123)456-7890, (123) 456-7890, (123) 456 - 7890, (123)4567890... that's what the current code does.
If you comment the current RegExp and uncomment the first one it will work just as you was asking for, accepting only a 10 digit input.
Related
I do match of words in a text to retrieve the word offset begin and end. This normally works for both ascii and unicode texts when using an appropriate unicode-aware regex like '(?<=^|\\PL)$1(?=\\PL|$)'. When I have mixed text (like Korean and English here) there are some problems, while tokenizing:
function aggressive_tokenizer(text) {
// most punctuation
text = text.replace(/([^\w\.\'\-\/\+\<\>,&])/g, " $1 ");
// commas if followed by space
text = text.replace(/(,\s)/g, " $1");
// single quotes if followed by a space
text = text.replace(/('\s)/g, " $1");
// single quotes if last char
text = text.replace(/('$)/, " $1");
text = text.replace(/(\s+[`'"‘])(\w+)\b(?!\2)/g, " $2")
// periods before newline or end of string
text = text.replace(/\. *(\n|$)/g, " . ");
// replace punct
// ignore "-" since may be in slang scream
text = text.replace(/[\\?\^%<>=!&|+\~]/g, "");
text = text.replace(/[…;,.:*#\)\({}\[\]]/g, "");
// finally split remainings into words
text = text.split(/\s+/)
return text;
}
var text = "점점 더 깊이 끌려가"
var tokens = aggressive_tokenizer(text);
var seen = new Map();
var indexes = tokens.map(token => { // for each token
let item = {
"word": token
}
var pattern = '(?<!\\pL\\pM*)$1(?!\\pL)';
var escaped = token.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
var wordRegex = new XRegExp(pattern.replace('$1', escaped), "g");
// calculate token begin end
var match = null;
while ((match = wordRegex.exec(text)) !== null) {
if (match.index > (seen.get(token) || -1)) {
var wordStart = match.index;
var wordEnd = wordStart + token.length - 1;
item.characterOffsetBegin = wordStart;
item.characterOffsetEnd = wordEnd;
seen.set(token, wordEnd);
break;
}
}
return item;
});
indexes.forEach(index => {
if (index.word != text.slice(index.characterOffsetBegin, index.characterOffsetEnd + 1)) {
console.log("NOT MATCHING!!! " + index.word + " : " + text.slice(index.characterOffsetBegin, index.characterOffsetEnd + 1))
} else {
console.log("\tMATCHED " + index.word + " : " + text.slice(index.characterOffsetBegin, index.characterOffsetEnd + 1))
}
});
<script src="https://unpkg.com/xregexp/xregexp-all.js"></script>
The problem is that I do some cleanup in tokenization like
text = text.replace(/([^\w\.\'\-\/\+\<\>,&])/g, " $1 ");
where \w is not unicode-aware, but if I replace it with \p{Alnum}:
text = text.replace(/([^\p{Alnum}\.\'\-\/\+\<\>,&])/g, " $1 ");
that it should be the equivalent for Unicode word, it does not work properly.
NOTE
Please note that I do use XRegExp to support Unicode regex in JavaScript.
UPDATE
According to the comments below, I have updated the code with the modified pattern regexp '(?<=^|\\PL)$1(?=\\PL|$)' by – Wiktor Stribiżew and replaced XRegExp with built-in RegExp, due to missing support for varied width lookbehind patterns (see comments).
This solution works better, but I have identified an additional case where the char offset begin and end cannot be matched for the given input text: "점점 더 깊이 끌려가" the output will have a missing offset / match for
{
"index": 2,
"word": "점"
}
function aggressive_tokenizer(text) {
// most punctuation
text = text.replace(/[^\w\.\-\/\+\<\>,&]/g, " $& ");
// commas if followed by space
text = text.replace(/(,\s)/g, " $1");
// single quotes if followed by a space
text = text.replace(/('\s)/g, " $1");
// single quotes if last char
text = text.replace(/('$)/, " $1");
text = text.replace(/(\s+[`'"‘])(\w+)\b(?!\2)/g, " $2")
// periods before newline or end of string
text = text.replace(/\. *(\n|$)/g, " . ");
// replace punct
// ignore "-" since may be in slang scream
text = text.replace(/[\\?\^%<>=!&|+\~]/g, "");
text = text.replace(/[…;,.:*#\)\({}\[\]]/g, "");
// finally split remainings into words
text = text.split(/\s+/)
return text;
}
var text = "점점 더 깊이 끌려가"
var tokens = aggressive_tokenizer(text);
var seen = new Map();
var indexes = tokens.map(token => { // for each token
let item = {
"word": token
}
var pattern = '(?<!\\pL\\pM*)$1(?!\\pL)';
var escaped = token.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
var wordRegex = new RegExp(pattern.replace('$1', escaped), "g");
// calculate token begin end
var match = null;
while ((match = wordRegex.exec(text)) !== null) {
if (match.index > (seen.get(token) || -1)) {
var wordStart = match.index;
var wordEnd = wordStart + token.length - 1;
item.characterOffsetBegin = wordStart;
item.characterOffsetEnd = wordEnd;
seen.set(token, wordEnd);
break;
}
}
return item;
});
indexes.forEach(index => {
if (!index.characterOffsetBegin && !index.characterOffsetEnd) {
console.log("MISSING INDEXES " + index.word);
} else if (index.word != text.slice(index.characterOffsetBegin, index.characterOffsetEnd + 1)) {
console.log("NOT MATCHING!!! " + index.word + " : " + text.slice(index.characterOffsetBegin, index.characterOffsetEnd + 1))
} else {
console.log("\tMATCHED " + index.word + " : " + text.slice(index.characterOffsetBegin, index.characterOffsetEnd + 1))
}
});
I'm currently using this to format an input text to have "-" after two characters and it replaces characters that are not "a-f" or "0-9" with "".
var macAddress = document.getElementById("macInput");
function formatMAC(e) {
var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
str = e.target.value.replace(/[^a-f0-9]/ig, "");
while (r.test(str)) {
str = str.replace(r, '$1' + '-' + '$2');
}
e.target.value = str.slice(0, 17);
};
macAddress.addEventListener("keyup", formatMAC, false);
I want it to also detect if the user writes ":" and replace it with "-", so it becomes impossible to write ":". Not sure how to accomplish this.
Easy. .split().join()
var macAddress = document.getElementById("macInput");
function formatMAC(e) {
var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
str = e.target.value.replace(/[^a-f0-9]/ig, "");
while (r.test(str)) {
str = str.replace(r, '$1' + '-' + '$2');
}
e.target.value = str.slice(0, 17).split(':').join('');
};
macAddress.addEventListener("keyup", formatMAC, false);
Enter : Samsung , Enter again : Samsung , Enter again: Tomas, Enter again: sass, Enter again : sass, Enter again: b, Enter again : b, Enter again : bb, Enter again : bb........
And to display the following :
With removeDuplicateUsingSet: Samsung, Tomas, sass, b, bb
Without the function : Samsung,Samsung,Tomas,sass,sass,b,b,bb,bb
and the loop to stop when you type stop.....
function removeDuplicateUsingSet(arr){
let unique_array = Array.from(new Set(arr))
return unique_array}
var inputs =[];
var alreadyEntered = false;
while (!alreadyEntered)
{
var input = prompt("Enter items until you enter it twice");
for (var i=0;i<inputs.length;i++) {
if (inputs[i] == input)
{
alert("Already entered!");
alreadyEntered = true;
break;
}
}
inputs.push(input);
}
alert("With removeDuplicateUsingSet function : " + "\n" +
removeDuplicateUsingSet(inputs) + "\n" + "Without: " + "\n" + inputs);
Now this code have break loop and i don't know how to fix it....
Tried doing this next thing :
function removeDuplicateUsingSet(arr){
let unique_array = Array.from(new Set(arr))
return unique_array
}
var array = [];
var stored = [];
while(array !== 'stop')
{
stored.push(prompt('what are your fav books ? '));
array = prompt('If you would like to continue enter any key otherwise enter or type stop');
// document.write(stored + " , ");
console.log(removeDuplicateUsingSet(array) + "\n___________");
}
alert("With removeDuplicateUsingSet function : " + "\n" +
removeDuplicateUsingSet(array) + "\n" + "Without: " + "\n" + stored);
but also not what i have been wanted....
It keeps removing all of the duplicate characters (ex. "Samsung" displays it SAMUNG,where i want to remove if there are entered 2 same elements(items)
Please help me.
Thanks in advance.
Is this your desired output?
function removeDuplicateUsingSet(arr) {
let unique_array = Array.from(new Set(arr))
return unique_array
}
var inputs = [];
while (true) {
var input = prompt("Enter items until you enter it twice");
if (input == 'stop') break;
inputs.push(input);
}
alert("With removeDuplicateUsingSet function : " + "\n" + removeDuplicateUsingSet(inputs) +
"\n" + "Without: " + "\n" + inputs);
I have a string for ex "adlkup.db.com" and I want to validate the string for ".com" at the end of the string.
var x = "adlkup.db.com";
So I am trying something like
/.com$/.test(x)
and the . is interpreting to some other regex which finds a single character, except newline or line terminator
A period in a regular expression matches any character.
To make it literal, you need to escape it:
/\.com$/.test('stackoverflow.com'); // true
/\.com$/.test('stackoverflowcom'); // false
Alternatively, as Racil Hilan points out in the comments, you can also use the .lastIndexOf() method in order to check:
var string = 'stackoverflow.com';
string.lastIndexOf('.com') === string.length - 4; // true
or using the .substr() method:
'stackoverflow.com'.substr(-4) === '.com'; // true
In ECMAScript 6 this is done with endsWith:
x.endsWith(".com");
There is a polyfill for old browsers.
After reading your comments, I think you can use this better than the regex:
var value1 = "adlkup.db.com";
var value2 = "adlkup.db.com.w3Schools";
var value3 = ".com";
document.write(value1 + " " + endWithCom(value1) + "<br/>");
document.write(value2 + " " + endWithCom(value2) + "<br/>");
document.write(value3 + " " + endWithCom(value3) + "<br/>");
function endWithCom(text){
if(text.length < 5)
return false;
return (text.substr(-4) == ".com");
}
And you can easily convert it to generic function so you can pass it any ending you want to check:
var value1 = "adlkup.db.com";
var value2 = "adlkup.db.com.w3Schools";
var value3 = ".com";
var value4 = "adlkup.db.org";
document.write(value1 + " " + endWithButNotEqual(value1, ".com") + "<br/>");
document.write(value2 + " " + endWithButNotEqual(value2, ".com") + "<br/>");
document.write(value3 + " " + endWithButNotEqual(value3, ".com") + "<br/>");
document.write(value4 + " " + endWithButNotEqual(value4, ".org") + "<br/>");
function endWithButNotEqual(text, ending){
if(text.length <= ending.length)
return false;
return (text.substr(-ending.length) == ending);
}
Seemed like an easy problem to solve. Cannot figure out why the code will return the secret word despite entering spaces or too many/too few characters. Need a little help. Thanx!
function secretWord() {
var text = "You entered";
var output = "Thank you, Po's secret word was validated";
<!--variable to hold secret word-->
var user_prompt = prompt("Enter Allen's secret word. It must contain exactly 7 characters and there can be no empty spaces", "");
do {
if(user_prompt.length == 6 && user_prompt.indexOf('') >= 0) {
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user.prompt.length < 6) {
window.alert("secret word is too short");
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user.prompt.length > 6) {
window.alert("secret word is too long")
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user_prompt.indexOf('') >= 0) {
window.alert("secret word cannot contain spaces");
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
}
while(user_prompt != -999);
}
Apart from the typos you have (user_prompt != user.prompt), you're looking for a 7-character string with no spaces.
What this condition checks:
if(user_prompt.length == 6 && user_prompt.indexOf('') >= 0) {
is a 6-character string with ANY character present.
What you need instead is:
if(user_prompt.length == 7 && user_prompt.indexOf(' ') == -1) {
This will be true if the string length is 7 and there are no spaces.
Here's a working example, I've simplified it a bit so it's easier to work with in a snippet here, but you can see and reuse the conditions:
function secretWord() {
var text = "You entered";
var output = "Thank you, Po's secret word was validated";
var user_prompt = prompt("Enter Allen's secret word. It must contain exactly 7 characters and there can be no empty spaces", "");
document.getElementById("guess").innerHTML = '';
if (user_prompt.length == 7 && user_prompt.indexOf(' ') == -1) {
document.getElementById("guess").innerHTML = text + "<br>" + user_prompt + "<br>" + output;
} else if (user_prompt.length < 7) {
document.getElementById("guess").innerHTML = "secret word is too short";
} else if (user_prompt.length > 7) {
document.getElementById("guess").innerHTML = "secret word is too long";
} else if (user_prompt.indexOf(' ') >= 0) {
document.getElementById("guess").innerHTML = "secret word cannot contain spaces";
}
}
<div id="guess"></div>
<button onclick="secretWord()">Run</button>
else if(user.prompt.length < 6) {
// ...
else if(user.prompt.length > 6) {
In both cases, user.prompt.length should be user_prompt.length
your problem is in else if statement
it should be user_prompt and not user.prompt
besides, even if you enter space yet exactly right amount of characters say 6 or so, it will pass the first if test.
you are not checking for space i.e. ' ' but ''. see to it you check for spaces properly.