I am currently making a senior memory book my English class, and because I'm a nerd I am going to put a bit of code in it. Well, I'm having a bit of trouble with regex in my code.
My entire code:
//For future reference, "alert(*parametes*)" will make an alert box with the parameters inside it.
//Asks you to enter a phrase and stores your answer.
var phrase = prompt("Enter a phrase to be checked for palindrome.").toLowerCase()
//Creates the entered phrase backwards.
var phraseBackwards = ""
for (var x in phrase) {
phraseBackwards += phrase[(phrase.length - 1) - x]
}
//Checks to see if the new phrase is a palindrome.
if (phraseBackwards == phrase) {
alert("The phrase you entered was a palindrome.")
}
//This happens if the preavious condition was false.
else {
//Checks if the new phrase is a palindrome without spaces.
if (phraseBackwards.replace("/\s+/g", '') == phrase) {
alert("The phrase you entered would have been a palindrome, had it not had spaces")
} else {
//Checks to see if the phrase you entered, even without spaces, is not a palindrome.
if (phraseBackwards.replace(/\s+/g, '') != phrase) {
alert("The phrase you ented was not a palindrome.")
}
}
}
The particular portion that is not functioning correctly:
//Checks if the new phrase is a palindrome without spaces.
if (phraseBackwards.replace(/\s+/g, '') == phrase) {
alert("The phrase you entered would have been a palindrome, had it not had spaces")
}
I realize that some of my code may not be optimal but I'm trying to hurry and finish because I procrastinated until last minute.
So there are a few points to note in my edit.
First of all, you need to remove all non word characters from the initial phrase using this: replace(/\W/g, "")
Then reverse the string: phrase.split("").reverse().join("")
Then check if phraseBackwards == phrase.
Note: The code you used to used to reverse the string was valid. But given your use for this, I thought you might want to make it shorter.
//For future reference, "alert(*parameters*)" will make an alert box with the parameters inside it.
//Asks you to enter a phrase and stores your answer.
var phrase = prompt("Enter a phrase to be checked for palindrome.").toLowerCase().replace(/\W/g, "");
//Creates the entered phrase backwards.
var phraseBackwards = phrase.split("").reverse().join("");
//Checks to see if the new phrase is a palindrome.
if (phraseBackwards == phrase) {
alert("The phrase you entered was a palindrome.");
}
//This happens if the previous condition was false.
else {
alert("The phrase you ented was not a palindrome.");
}
phraseBackwards without spaces can't be == to the original phrase, because the original has spaces. Remove spaces from the original phrase as well. – Jeremy Thille
Related
This is a two part question, I currently have the below code and I'm trying to have it so that the console will tell me if it is a lower case letter or an upper case letter or of it is a number. I cant seem to get the number.isInteger to work so please tell me where I am going wrong with that.
Also I would like to have it so that there is a call back of what the user entered. So instead of it just saying "This is a upper case letter" I would like it to state "The letter g you entered is lowercase" and vice versa for upperCase and numbers.
Hope that makes sense, please find below my current code. I am new to coding and javascript so please try dumb it down as much as possible for me. Thanks!
Please see below code I currently have:
let upperLower = prompt("please enter either a uppercase letter, lowercase letter or a number");
if (upperLower == upperLower.toLowerCase()) {
console.log("The character is lowercase");
}
else if (upperLower == upperLower.toUpperCase()) {
console.log("The character is uppercase");
}
else if (upperLower == Number.isInteger()){
console.log("This is a number");
}
Or you can check if input converted to number is not a number (isNaN) is false
let upperLower = prompt("please enter either a uppercase letter, lowercase letter or a number");
if (!isNaN(parseInt(upperLower))){
console.log(upperLower + " is a number");
}
else if (upperLower == upperLower.toLowerCase()) {
console.log(upperLower + " character is lowercase");
}
else if (upperLower == upperLower.toUpperCase()) {
console.log(upperLower + " character is uppercase");
}
A palindrome is a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or reverse direction. Famous examples include "Amore, Roma", "A man, a plan, a canal: Panama" and "No 'x' in 'Nixon'". - wikipedia
Our goal is to determine whether or not a given string is a valid palindrome or not.
Test cases:
Test.assertEquals(palindrome("Amore, Roma"), true)
Test.assertEquals(palindrome("A man, a plan, a canal: Panama"), true)
Test.assertEquals(palindrome("No 'x' in 'Nixon'"), true)
Test.assertEquals(palindrome("Abba Zabba, you're my only friend"), false)
My code so far:
function palindrome(string) {
var str = string.toLowerCase().replace(/[^a-z]+/g,"");
var rev= str.split("").reverse().join("");
if (string == rev) {
return true;
} else {
return false;
}
}
Apparently join is undefined but I don't understand why?
I tried your examples with the following changes and it works on OSX 10.9:
function palindrome(string) {
var str = string.toLowerCase().replace(/[^a-z]/g, "");
var rev = str.split("").reverse().join("");
return (str == rev);
}
It appears the array join() method has been part of Javascript since version 1.1 -- both the specific error message and some description of your environment should help resolve this.
I know this kind of question has been asked several times but none of the answers worked for me. I want to make my own spell-checker which compares words letter by letter and checks the correctness.
As user types letters one by one, the content is checked. If it is correct, goes on, if it is wrong: I want the last letter to be deleted.
Here is my code:
var word = [];
word = "beautiful".split('');
var i =0;
$(document).ready(
function()
{ $('#txtword').keyup(
function() {
var value = document.getElementById('txtword').value;
if (value[i] == word[i]){
alert("Right letter!");
i++; }
else
{ alert("Wrong letter");
value.slice(0,-1);
/*value.substr(0,value.length-1);*/
}
});
})
I tried both options value.slice(0,-1); and value.substr(0,value.length-1); but they are not working. Can someone help me find the mistake!
You need to assign new value back to value property of the element
this.value = value.substr(0,value.length-1);
Note: You can use this.value instead of document.getElementById('txtword').value;
I wanted to allow only characters in a textbox and space in between two characters.I am trying to avoid any unwanted characters and blank string in following Javascript code.
var filter = "^[a-zA-Z''-'\s]{1,40}$";
var label = $('#<%= txtName.ClientID %>').val();
if ((label.length > 0) && (label!= '')) {
if (label.match(/^[a-zA-Z \s]{1,40}$/)) {
if (label.match(/^\s$/)) {
alert("Please Enter a Valid name");
return false;
}
else {
$("#myModal").dialog('open');
}
}
else {
alert("Please Enter a Valid name");
}
}
else {
alert("Please Enter a Valid name");
}
This is working fine for everything except when user enters more than 1 space in the textbox. I was thinking that label.match(/^\s$/)) will take care of blank string or blank spaces.
Thanks
It looks like this is a job for 0 or more (the RegEx *)! (Pardon the exclamation, I'm feeling epic this morning)
/^\s$/ means "contains only one space"
I believe you are looking for
/^\s*$/ means "contains only zero or more spaces"
you should use + sign in regular expression for more than one entities.suppose if you want multiple spaces then use like var expr=/(\s)+/
What I'm trying to do is make a loop which prompts the user for information and will only stop if certain strings are entered. Specifically, I want it only to accept certain letters, both upper and lowercase. Here's what I have so far:
do
{
salesP = prompt("Enter the initial of the first name of the salesperson: ", "");
}while (salesP != "C" || salesP != "c")
Basically the while part is completely wrong and I know it. I've tried everything I can think of, and the best I can do is get it to accept a single variable. I also need it to accept d, x, and m, both cases.
Option 1
Permanent loop with an if statement, can use multiple if statements or other control structures to check for when to break.
while 1:
if(raw_input('Enter some data please:') == specialString):
break
Option 2
Part of loop
tempstring = ""
while (tempstring != specialString):
tempstring = raw_input('Enter some data please:')
Option 3:
Recursion
def dataEntry(a,b,c):
#data validation statements that fail on first iteration
#statements to prompt user about data
dataentry(a,b,c)
As far as how to check for the right string, I would recommend regular expressions. Googling for "regex" examples is much better than me trying to explain it.
Something else to play with that if you are new you should become REALLY familiar with when doing string comparison is to eliminate case from the equation completely:
do
{
salesP = prompt("Enter the initial of the first name of the salesperson: ", "");
}while (salesP.toLowerCase() != 'c')
That code is almost correct. You simply use the incorrect boolean operator in your while statement. You're using OR (||) where you should use AND (&&).
So:
do
{
salesP = prompt("Enter the initial of the first name of the salesperson: ", "");
}while (salesP != "C" && salesP != "c")
just another approach
function promptSalesP(){
var _salesP = prompt("Enter the initial of the first name of the salesperson: ", "");
if(_salesP.toLowerCase() == "c")
return _salesP;
else
return promptSalesP();
}
var salesP = promptSalesP();