The max size of textbox is given as 11. I want to print first 4 characters as alphabets and next 7 characters as numbers. Please give me a solution in javascript only.
function Myfunction2() {
var x2 = document.getElementById('text').value;
var re = /^[A-za-z]+$/;
for (i = 0; i < 4; i++) {
y = x2charAt(i);
if (re.test(x2.value)) {
alert("please enter char only");
}
}
}
function Myfunction() {
var x = document.getElementById("text").value;
for (i = 5; i < 11; i++) {
y = x.charAt(i);
if (y == " " || isNaN(y)) {
alert("not numeric");
}
}
}
Test it against an expected pattern:
/^[a-z]{4}[0-9]{7}$/i.test(value);
You could bind this to the actual input element as well to test it with each keystroke:
var supercode = document.getElementById("supercode"),
rePattern = /^[a-z]{4}[0-9]{7}$/i;
supercode.addEventListener("keyup", function(e){
this.style.borderColor = rePattern.test(this.value) ? "green" : "red" ;
}, false);
Demo: http://jsfiddle.net/RfMK7/
Related
I'm trying, and failing, to check for whether or not a 5-digit integer is a palindrome or not using javascript. I have gotten the code to correctly check for 5-digit strings (not integers yet). That part should be relatively easy to figure out.
My main question: Am I doing the structure for using functions in javascript? If so, how can I get the function call to work properly? It just quits the program upon receiving the desired input.
Code is as follows:
<script type="text/javascript">
var userInput;
var counter = 0;
function palindrome(userInput) {
var re = /[^A-Za-z0-9]/g;
userInput = userInput.toLowerCase().replace(re, '');
var len = userInput.length;
for (var i = 0; i < len/2; i++) {
if (userInput[i] !== userInput[len - 1 - i]) {
return false;
}
}
return true;
}
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
palindrome(userInput);
while (counter < 10){
if (userInput.length == 5){
if (pandindrome(userInput) == true){
document.write("The input is a palindrome!");
}
else if (pandindrome(userInput) == false){
document.write("The input is not a palindrome! Try again!");
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
palindrome(userInput);
}
counter++;
}
else if (userInput.length != 5){
alert("The input you entered was not 5-digits! Please try again!");
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
palindrome(userInput);
}
}
</script>
I have tested your code, everything works fine!
FIY, I set a variable isPalindrome to store the return value from the function palindrome. Then you can use it directly inside if statement, instead of compare to true.
var userInput;
var counter = 0;
function palindrome(userInput) {
var re = /[^A-Za-z0-9]/g;
userInput = userInput.toLowerCase().replace(re, "");
var len = userInput.length;
for (var i = 0; i < len / 2; i++) {
if (userInput[i] !== userInput[len - 1 - i]) {
return false;
}
}
return true;
}
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
var isPalindrome = palindrome(userInput);
while (counter < 10) {
if (userInput.length == 5) {
if (isPalindrome) {
document.write("The input is a palindrome!");
} else {
document.write("The input is not a palindrome! Try again!");
userInput = window.prompt(
"Please enter a 5-digit, numerical palindrome: "
);
isPalindrome = palindrome(userInput);
}
counter++;
} else if (userInput.length != 5) {
alert("The input you entered was not 5-digits! Please try again!");
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
isPalindrome = palindrome(userInput);
}
}
A lot of solutions I found here are giving true or false after checking if a string is a palindrome. I have a function that checks if a string is a palindrome or not:
function palindrome(myString){
/* remove special characters, spaces and make lowercase*/
var removeChar = myString.replace(/[^A-Z0-9]/ig, "").toLowerCase();
/* reverse removeChar for comparison*/
var checkPalindrome = removeChar.split('').reverse().join('');
/* Check to see if myString is a Palindrome*/
if(removeChar === checkPalindrome){
document.write("<div>"+ myString + " is a Palindrome <div>");
}else{
document.write("<div>" + myString + " is not a Palindrome </div>");
}
}
palindrome("Oh who was it I saw, oh who?")
palindrome("Madam")
palindrome("Star Wars")
But this is not quite what I want. It's just checking if the string is a palindrome or not. I want to update the function so that it identifies all of the palindromes in a sentence instead of giving it true or false. So if there's a sentence like this - "Madam and John went out at noon" It will list the palindromes in that sentence - "Madam, noon"
Any help in this would be appreciated!
function findPalindromes(str, min) {
min = min || 3;
var result = [];
var reg = str.toLowerCase();
var reg = reg.replace(/[^a-z]/g, ''); // remove if you want spaces
var rev = reg.split("").reverse().join("");
var l = reg.length;
for (var i = 0; i < l; i++) {
for (var j = i + min; j <= l; j++) {
var regs = reg.substring(i, j);
var revs = rev.substring(l - j, l - i);
if (regs == revs) {
result.push(regs);
}
}
}
return result;
}
var str1 = "Madam and John went out at noon";
console.log(str1, findPalindromes(str1));
var str2 = "\"Amore, Roma\" and \"There's no 'x' in Nixon\" are palindromes.";
console.log(str2, findPalindromes(str2));
function findPalindromes(sentence) {
const words = sentence.replace(/[^\w\s]/gi, '').split(' ');
const palindromes = words.filter(isPalindrome);
return palindromes;
}
function isPalindrome(word) {
if (word.length <= 0) return false;
word = word.toLowerCase();
for (let i = 0; i < word.length / 2; i++) {
if (word[i] !== word[word.length - 1 - i]) return false;
}
return true;
}
https://jsfiddle.net/ewezbz22/1/
Hi I am looking to compare two strings and have all the lowercase letters in string B -which are uppercase letters in string A- to uppercase, the problem with my code is it only changes the last letter like this
var i;
var x;
function switchItUp(before, after) {
for (i = 0; i < before.length; i++) {
if (before.charAt(i) == before.charAt(i).toUpperCase()) {
x = after.replace(after.charAt(i), after.charAt(i).toUpperCase());
}
}
console.log(x);
}
switchItUp("HiYouThere", "biyouthere");
this will result in "biyouThere" any way to change it to "HiYouThere" ?
I have modified your code correctly to work. You needed to apply the operation to the same variable, x, not after, in every loop.
function switchItUp(before, after) {
var x = after;
for (i = 0; i < before.length; i++) {
if (before.charAt(i) == before.charAt(i).toUpperCase()) {
x = x.replace(after.charAt(i), after.charAt(i).toUpperCase());
}
}
console.log(x);
}
You have to assign each changes. It's working now
var i;
var x;
function switchItUp(before, after) {
for (i = 0; i < before.length; i++) {
if (before.charAt(i) == before.charAt(i).toUpperCase()) {
x = after.replace(after.charAt(i), after.charAt(i).toUpperCase());
after = x;
//console.log("inside"+x);
}
}
console.log(x);
}
switchItUp("HiYouThere", "biyouthere");
This is code:
function switchItUp(before, after) {
for (var i = 0; i < before.length; i++) {
if (before.charAt(i) == before.charAt(i).toUpperCase()) {
after = after.replace(after.charAt(i), after.charAt(i).toUpperCase());
}
}
return after;
}
var after = switchItUp("HiYouThere", "biyouthere");
document.body.innerHTML+='<p style="color: black;">'+ after + '<p/>';
How can I modify the script below so that it alerts not only when the field is empty, but when the field is empty or contains less than 10 digits (it can contain anything, not only digits)?
if (myform.mytextinput.value=="")
alert ('Please enter something!");
A good script that checks for ten digits is this:
var input_dg = document.getElementById("mytextinput");
var text_dg = input_dg.value;
var totalNrOfDigits = 0;
for(var i = 0; i < text_dg.length; i++){
if(/\d/.test(text_dg[i])){
totalNrOfDigits++;
}
}
alert ('Please enter at least 10 digits!');
I just need to "paste" the second script in the first, but I lack the know-how. Both scripts are inside a large form validation script...
Just use ||, the OR operator:
if (myform.mytextinput.value=="" || myform.mytextinput.length < 10)
To count the number of digits in a string I recommend this code (From this SO answer):
var totalNrOfDigits = myform.mytextinput.replace(/[^0-9]/g,"").length;
// And now combine both checks:
if (myform.mytextinput.value=="" || totalNrOfDigits < 10){
// Alert the user
}
If you want to use the same code you were using you only need to replace the first part:
var input_dg = document.getElementById("mytextinput");
var text_dg = input_dg.value;
var totalNrOfDigits = 0;
for(var i = 0; i < text_dg.length; i++){
if(/\d/.test(text_dg[i])){
totalNrOfDigits++;
}
}
if (myform.mytextinput.value=="" || totalNrOfDigits < 10){
// Alert the user
}
Try this using the OR(||):
if (myform.mytextinput.value=="" || myform.mytextinput.length < 10)
You can count them with a regex
var str ='1a2b3',
digits = (str).match(/\d+/g); // returns ["1", "2", "3"]
if ((! str.length) || (! digits) || (digits.length < 10)) {
alert ('Please enter at least 10 digits!');
}
Did you want this?
var input_dg = document.getElementById("mytextinput");
var text_dg = input_dg.value;
if(text_dg == "") {
alert ('Please enter something!');
} else if(text_dg.length < 10) {
alert("Please enter at least 10 digits!");
}
Fiddle.
I'm trying to create a password generator based on the options provided by the user. My current script allows users to select uppercase, lowercase, numeric and special characters. This works perfectly and strings are generated to to the user's required length however upon generation, numbers cluster at the string with letters clustering at the beginning. A single special character parts the two. Do you have any suggestions on how to improve the process?
$('document').ready(function() {
$('button').click(function() {
var lower = "";
var upper = "";
var numeric = "";
var special = "";
var string_length = "";
if($('#12').is(':checked')) { string_length = 12; };
if($('#16').is(':checked')) { string_length = 16; };
if($('#18').is(':checked')) { string_length = 18; };
if($('#22').is(':checked')) { string_length = 22; };
if($('#24').is(':checked')) { string_length = 24; };
if($('#custom').is(':checked')) { $('#custom').show(); $('#custom').val(); } else { $('#custom').hide(); };
if($('#ch1').is(':checked')) { lower = "abcdefghijklmnopqrstuvwxyz"; } else { lower = ""; };
if($('#ch2').is(':checked')) { upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; } else { upper = ""; };
if($('#ch3').is(':checked')) { numeric = "0123456789"; } else { numeric = ""; };
if($('#ch4').is(':checked')) { special = "!£$%^&*()_-+={};:#~#?/"; } else { special = ""; };
var chars = lower + upper + numeric + special;
var randomstring = '';
var charCount = 0;
var numCount = 0;
for (var i=0; i<string_length; i++) {
if((Math.floor(Math.random() * 2) == 0) && numCount < 3 || charCount >= 5) {
var rnum = Math.floor(Math.random() * 10);
randomstring += rnum;
numCount += 1;
} else {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
charCount += 1;
}
}
$('span.string').html(randomstring);
});
});
The options 16 length, lowercase, uppercase, numeric and special characters returns something like e046pzw%65760294.
This line is your culprit:
if((Math.floor(Math.random() * 2) == 0) && numCount < 3 || charCount >= 5) {
It says:
The first 3 characters have a bit over 50/50 chance of being numbers. The "then" is always a number and the "else" is a number sometimes depending on options.
After you have 5 "else" selected chars (which means after col 8), you will always have a number.
This is because the "&&" takes precedence over the "||". I suggest using some parentheses to surround the OR clause if you want to have a 50/50 plus chance of using the digit. I also included an alternate way to do 50/50.
if ((Math.random() < 0.5) && (numCount < 3 || charCount >= 5)) {
I'm not sure why you want numbers to have precedence.
An alternative solution. Just my five cents:
$(function(){
$('input, select').change(function(){
var s = $('input[type="checkbox"]:checked').map(function(i, v){
return v.value;
}).get().join(''),
result = '';
for(var i=0; i < $('#length').val(); i++)
result += s.charAt(Math.floor(Math.random() * s.length));
$('#result').val(result);
});
});
Just to give you some ideas. I'm fully aware of that this doesn't take any "type count" in to consideration.
http://jsfiddle.net/m5y3e/