JavaScript - How to determine if a letter is surrounded by a symbol? - javascript

I am trying to solve a JavaScript coding exercise and my code is wrong and I can't see why.
The task is:
take a string and if every letter in the string is surrounded by a '+' sign, return true, otherwise return false.
It works for most cases but doesn't work for '=a+' for example and I don't understand why. Could someone explain?
function SimpleSymbols(str) {
for (var i = 0; i < str.length; i++) {
if (str[0].match(/[a-z]/i) || str[str.length - 1].match(/[a-z]/i)) {
return false;
} else {
if (str[i].match(/[a-z]/i) && (str[i - 1] !== "+" || str[i + 1] !== "+")) {
return false;
} else {
return true;
}
}
}
}
SimpleSymbols(readline());

The issue is the inner else clause. It should be elimninated, and instead, the function should return true after the for block.
function SimpleSymbols(str) {
for (var i = 0; i < str.length; i++) {
if (str[0].match(/[a-z]/i) || str[str.length - 1].match(/[a-z]/i)) {
return false;
} else {
if (str[i].match(/[a-z]/i) && (str[i - 1] !== "+" || str[i + 1] !== "+")) {
return false;
}
}
}
return true;
}

Could you match against this and return the result:
^\+(?:[a-z]\+)*$
https://regex101.com/r/1zXUJD/1
looks for strings that start with a '+' and then any number of [a-z]+ after that until the end of the string.

Related

Finding if a given set of parentheses is valid or not

Below is my code, it works for some strings but not for all.
Ex: "()()()()()((" expected is false, my code returns true.
function validParentheses(parens){
var stack = [];
parens.split('').map((cur, index) =>{
if(stack.length === 0 || stack[index-1] === cur) stack.push(cur);
else stack.pop();
});
return stack.length > 0 ? false : true;
}
stack[index - 1] will be valid so long as you push every iteration. In the case that you pop an element, the incrementing index will always be out of bounds.
Change it to stack.length - 1 to always get the last element, regardless of what is pushed or popped.
For every '(' there must be a exactly one ')'. So you need a counter to see that there is an exact match
function validParentheses(parens){
const chars = parens.split('');
const numChars = chars.length;
let ii;
let numOpenParens = 0;
for (ii = 0; ii < numChars; ii += 1) {
curChar = chars[ii];
numOpenParens += curChar == '(' ? 1 : -1;
// return false if there is one too many closed parens
if (numOpenParens < 0) {
return false;
}
}
// return true only if all parens have been closed
return numOpenParens === 0;
}
For case when stack's length is greater than 0:
if top of the stack is equal to current iterated parenthesis, push that to stack
else pop the stack
function validParentheses(parens) {
var stack = []
parens.split("").forEach((cur) => {
if (stack.length > 0) {
if (stack[stack.length - 1] === cur) {
stack.push(cur)
} else {
stack.pop()
}
} else {
stack.push(cur)
}
})
return stack.length > 0 ? false : true
}
console.log(validParentheses("()()()()()(("))
console.log(validParentheses("()()()()()()"))
console.log(validParentheses("((()))"))
console.log(validParentheses("((())))"))
in stack[index-1] === cur
you are comparing if the char isn't the same like the one stored in the stack, so )( opposite parens will be valid
you can try do something like this
function validParentheses(parens) {
if (parens % 2 == 1) return false;
for (let i = 0; i < parens.length; i++) {
const char = parens[i];
if (char == "(") {
if (parens[i + 1] == ")") {
i++;
} else {
return false
}
} else {
return false
}
}
return true;
}
You need to check the last added value as well, because an unresolves closing bracket should remain in he stack.
BTW, Array#forEach is the method of choice, because Array#map returns a new array, which is not used here.
function validParentheses(parens) {
var stack = [];
parens.split('').forEach((cur, index) => {
if (cur === ')' && stack[stack.length - 1] === '(') stack.pop();
else stack.push(cur);
});
return !stack.length;
}
console.log(validParentheses("(())()"));
console.log(validParentheses("()()()()()(("));
console.log(validParentheses("))(())"));

How to check if a character is a letter or a number in javascript?

I am new to javascript I'm trying to check user entered the alphabet or a number.
if the user enters "A" it shows Alphabet it's ok but if the user enters "1" I want to show Number but its show alphabet.
where i done wrong.
Thanks Advance
function CHECKCHARATCTER(Letter) {
if (Letter.length <= 1) {
if ((64 < Letter.charCodeAt(0) < 91) || (96 < Letter.charCodeAt(0) < 123)) {
return "Alphabhate";
}
else if (47 < Letter.charCodeAt(0) < 58) {
return "NUMBER";
}
else { return "Its NOt a NUMBER or Alphabets"; }
}
else { return ("Please enter the single character"); }
}
a = prompt("enter the number or Alphabhate");
alert(typeof (a));
b = CHECKCHARATCTER(a);
alert(b);
Here:
if (64 < Letter.charCodeAt(0) < 91) //...
JS isn't Python. You can't simply do a < b < c, you need to explicitly use the logical && operator: (a < b) && (b < c).
You can use regular expressions. Please have a look at regular expressions. It will be very helpful.
function checkAlphaNum(char) {
let alphaReg = new RegExp(/^[a-z]/i);
let numReg = new RegExp(/^[0-9]/);
if(alphaReg.test(char)) {
return "ALPHABET";
} else if(numReg.test(char)) {
return "NUMBER";
} else {
return "OTHER";
}
}
console.log("Output : ", checkAlphaNum('A'));
console.log("Output : ", checkAlphaNum(1));
I modified you conditions as it's shown in the following code. Also you can check it out here
function CHECKCHARATCTER(Letter){
if (Letter.length <= 1)
{
if (Letter.toUpperCase() != Letter.toLowerCase()) {
return "Alphabet";
}
else if (!isNaN( Letter)) {
return "Number";
} else{
return "Its Not a Number or Alphabet";
}
}
else {
return("Please enter the single character");
}
}
input = prompt("enter the Number or Alphabet");
output = CHECKCHARATCTER(input);
alert(output);

Validate Credit card without regExp

I am trying to validate credit card number which may contain four tests of alphanumeric characters, separated by hyphens (-) or without hyphens. Not using regExp.
I have tried different ways but I can't figure out how to do it properly.
That's what I have done so far:
function isCredit(input) {
var i, code;
//if input.length > 19, stop execution
if(input.length > 19) return false;
for(i = 0; i < input.length; i++) {
code = input.charCodeAt(i);
//Matches to only numbers and Capital letters
if((code > 47 && code < 58) && (code > 64 && code < 91)) {
//if every 5th character is "-"
if((input.slice(4, 5) === "-") && (input.slice(9, 10) === "-") &&(input.slice(14, 15) === "-")) {
return true;
}
}
return false;
}
}
isCredit("12A4-56H8-43K6-36U3"); // returns true;
isCredit("4427A693CF324D14"); // returns true;
isCredit("----------------"); // returns false;
Any help and guidance appreciated!
I'm not exactly clear on your requirements. Here I'm assuming "12A556H8-43K636U3" is a valid card number if you allow hyphen omissions.
function isAlphaNum(ch) {
var code = ch.charCodeAt(0);
return ((code > 47 && code < 58) || (code > 64 && code < 91));
}
function isCard(str) {
var char, i = 0, x = [1,1,1,1,0,1,1,1,1,0,1,1,1,1,0,1,1,1,1];
while (char = str[i++]) {
if (x[0] == undefined) {
return false;
}
if (isAlphaNum(char)) {
if (x[0]) {
x.shift();
} else {
x.splice(0,2);
}
} else if (char == '-') {
if (!x[0]) {
x.shift();
} else {
return false;
}
} else {
return false;
}
}
return x[0] == undefined;
}

Javascript palindrome check word to see if it's a palindrome

I'm trying to determine if a word is a palindrome. A palindrome is a word that is spelled the same way forwards and backwards. I want my code to console.log what I've written but I'm getting an error: unreachable code after return statement.
The line where error starts is: isWordAPalindrome('word');?
isWordAPalindrome('word');
function isWordAPalindrome(word) {
var word = "sherpa,stewie,anna,lil squiggle, racecar, tacocat"
str[0];
str.length
console.log(); {
if (str.length = 0) {
return true;
}
if (str[0] != str[str.length - 1]) {
return false;
}
return isWordAPalindrome(str.slice(1, str.length - 1));
isWordAPalindrome('word');
console.log('sherpa');
console.log('stewie');
console.log('anna');
console.log('lil squiggle');
console.log('racecar');
console.log('tacocat');
}
console.log(''); //simply making a newline for easier console reading
console.log('The word provided is: ', word);
isWordAPalindrome('sherpa');
console.log('sherpa is not a palindrome');
isWordAPalindrome('stewie');
console.log('stewie is not a palindrome');
isWordAPalindrome('anna');
console.log('anna is a palindrome');
isWordAPalindrome('lil squiggle');
console.log('lil squiggle is not a palindrome');
isWordAPalindrome('racecar');
console.log('racecar is a palindrome');
isWordAPalindrome('tacocat');
console.log('tacocat is a palindrome');
}
Different approach:
const word = "sherpa,stewie,anna,lil squiggle, A butt tuba, racecar, tacocat";
const a = word.split(',').map(s => s.toLowerCase().replace(/\s+/g, ""));
const isP = s => s === s.split('').reverse().join('');
for (let w of a) {
console.log(`${w}: ${isP(w)}`)
}
You have a return statement which stops the code execution and returns from the function.
Here what you want to achieve
function checkPalindrome(word) {
for (var i = 0, j = word.length -1; i++, j--; i < word.length, j >= 0, i < j) {
if (word.charAt(i) !== word.charAt(j)) {
return false;
}
}
return true;
}
console.log(checkPalindrome('sherpa'));
console.log(checkPalindrome('anna'));
You have code inside the isWordAPalindrom method that is after the return:
return isWordAPalindrome(str.slice(1,str.length-1));
//unreachable
isWordAPalindrome('word');
console.log('sherpa');
console.log('stewie');
...
that code is unreachable
Your recursive routine is fine. You just need to know where to start and end your tabs and braces.
Also, you were assigning the value 0 to your str.length instead of evaluating if it was equal (=== or at the very least ==).
Also, you can evaluate if the word is a palindrome before your print out the log message.
var words = "sherpa, stewie, anna, lil squiggle, racecar, tacocat".split(/,\s*/);
words.forEach(word => {
var isPalindrome = isWordAPalindrome(word);
console.log(`${word} is ${!isPalindrome ? 'not ' : ''}a palindrome`);
});
function isWordAPalindrome(str) {
if (str.length === 0) {
return true;
}
if (str[0] != str[str.length - 1]) {
return false;
}
return isWordAPalindrome(str.slice(1, str.length - 1));
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Output
sherpa is not a palindrome
stewie is not a palindrome
anna is a palindrome
lil squiggle is not a palindrome
racecar is a palindrome
tacocat is a palindrome
When you do return you are doing your thread "go out" of the function.
Code after return can't be ever executed, it is what the error is saying to you.
If you are trying to do something before the return statement, just put it before.
isWordAPalindrome('word');
console.log('sherpa');
console.log('stewie');
console.log('anna');
console.log('lil squiggle');
console.log('racecar');
console.log('tacocat');
return isWordAPalindrome(str.slice(1, str.length - 1));

Failed test for JavaScript palindrome

I noticed when I literally type the word test or dabd, it fails by saying "test is a palindrome"; obviously these should fail. I test other words like racecar, madam, cat, they all pass. I check from the left most character and right most character and go down until we reach the middle. What could be the issue?
function lengthChecker() {
var str = document.getElementById("str").value;
if (str.length > 10) {
alert("Sorry. Your input surpasses the 10 characters maximum. Please try again.")
return false;
} else if (str.length == 0) {
alert("Sorry. Your input is too short, and doesn't meet the 10 characters maximum. Please try again.")
return false;
}
palindrome(str);
}
function palindrome(str) {
var j = str.length;
if (/\s/.test(str)) {
alert("No spaces allowed.")
return false;
}
for (i = 0; i < j / 2; i++) {
if (str[i] == str[j - 1 - i]) {
isPalindrome('', str);
return true;
} else {
notPalindrome(str);
return false;
}
}
}
function isPalindrome(e, str) {
alert(str + " is a Palindrome.");
}
function notPalindrome(str) {
alert(str + " isn't a Palindrome");
}
document.addEventListener("DOMContentLoaded", function(e) {
var el = document.getElementById("checkInput");
el.addEventListener("click", lengthChecker);
});
In palindrome() you always only check the first character and immediately return. Fix the loop like this:
for (var i = 0; i < j / 2; i++) {
if (str[i] != str[j - 1 - i]) {
notPalindrome(str);
return false;
}
}
isPalindrome('', str);
return true;
For reference, you don't need to loop. You can simplify the palindrome test to just this:
str === str.split('').reverse().join('')
This splits the string into an array, which can then be reversed. It then joins it back into a string so you can compare it.
I'd then put this in a ternary statement for modifying the message:
var notp = (str === '' || str !== str.split('').reverse().join('').replace(" ", "")) ? 'is NOT':'IS';
I added "str === ''" to test for non-entries, and I added a remove spaces test as well. Now you've got a variable that you can push into a generic alert or whatever. You can change that to read "true:false;" instead is you want to control more than just the text of the message.
The following gets rid of the leading and trailing spaces:
str = str.trim();
There are more edits you can make, but this should help you along. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/fudLdx0r/

Categories