My Palindrome checker function works for single strings i.e. 'dog' it works, but when it is a phrase i.e. 'nurses run' it does not work! here is my code:
function palindromeCheck(string) {
return string === string.split('').reverse().join('');
}
function palindromeCheck(string) {
string = string.replace(/\s+/g,'');
return string === string.split('').reverse().join('');
}
The s+ character means to match any number of whitespace characters (including tabs). The g character means to repeat the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
Try this.
function palindromeCheck(string) {
string = string.replace(/\s/g, "");
return string === string.split('').reverse().join('');
}
console.log(palindromeCheck('nurses run'))
Related
I'm trying to make a function that will check if a word is a palindrome. If the word is a palindrome it will return true else it will return false. "You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes.
We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others."
My code is:
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-z]+/g,"");
if (str === str.split("").reverse().join("")){
return str;
} else {
return "This is not a palindrome";
}
}
Could somebody tell me what is wrong with this code please?
How about this solution.
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-z0-9]+/g,"");
return str === str.split("").reverse().join("");
}
It strips non alpha-numeric characters, turns into lower case, and returns true | false
"alphanumeric" means both alphabetical and numerical characters. Try something like this:
function isPalindrome(str) {
str = str.toLowerCase().replace(/[^a-z0-9]+/g, '');
return str === str.split('').reverse().join('');
}
isPalindrome('racecar')
// => true
isPalindrome('race car')
// => true
isPalindrome('race caR')
// => true
It doesn't work because it always return a "true" because if not palindrome, then return a string, which evaluated as a boolean is true.
Trying to make sure no one put a space in the username on sign up, I got the html tags to removed but not spaces.
Javascript:
$("#user").keypress(function (evt) {
if (isValid(String.fromCharCode(evt.which)))
return false;
});
function isValid(str) {
return /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
function stripspaces(input) {
input.value = input.value.replace(/\s/gi, "");
return true;
}
HTML:
Username: <input type="text" id="user"><br/>
You can see it here. http://jsfiddle.net/QshDd/63/
You can try with (each space character is being replaced, character by character, with the empty string):
str = str.replace(/\s/g, '');
or (each contiguous string of space characters is being replaced with the empty string by the "+" character):
str = str.replace(/\s+/g, '');
Ciao!
try this,
input.value.replace(/\n/g," ").replace( /<.*?>/g, "" );
You need to return the input value with the spaces removed:
function stripspaces(input)
{
return input.value.replace(/\s/gi,"");
}
The way you had it written the function just returned true regardless. Also, it seems you weren't calling the function (admittedly from only a quick read).
Although, it's probably easier to simply add \s (a regular expression special character for white-space characters) to the characters to replace, giving:
function isValid(str) {
return /[~`!#$%\^&*+=\-\[\]\\';,/\s{}|\\":<>\?]/g.test(str);
}
JS Fiddle demo.
References:
JavaScript regular expressions.
this program is supposed to test str, and if every letter in str has a '+' sign on both sides of it then the function should return true. Otherwise, it should return false. I keep getting the error "SyntaxError: invalid quantifier".
function SimpleSymbols(str) {
var boolean = false;
for(var i=1;i<(str.length-1);i++){
if(/\w/.test(str.charAt(i))){
if(str.charAt(i-1).match('+') && str.charAt(i+1).match('+')){
boolean = true;
}else{
boolean = false;
}
}
}
str = boolean;
return str;
}
match is used for regular expressions, so it's trying to convert '+' to a regular expression, but it's failing because /+/ isn't a valid regular expression (it should be '\\+' or /\+/). But it's easier to just directly test each character, like this:
if(str.charAt(i-1) == '+' && str.charAt(i+1) == '+'){
Also note that /\w/ matches any 'word' character, which includes letters, numbers, and underscores. To mach just letter characters use should use /[a-z]/i (the i at the end makes it case-insensitive, so it will also match upper-case letters).
But it seems a lot simpler to invert the condition. Just test to see if the string contains any letter not surrounded by + signs or a letter at the beginning or end of the string, and return false if it does, like this:
function SimpleSymbols(str) {
return ! /(^|[^+])[a-z]|[a-z]([^+]|$)/i.test(str);
}
Much easier:
function SimpleSymbols(str) {
return !str.match(/[^+]\w/) && !str.match(/\w[^+]/);
}
The main problems with your function are:
You don't test if the first and last characters are letters. It should be safe to run your for loop from index 0 to < str.length because even though this will result in a str.charAt(-1) and str.charAt(str.length) when testing for '+' these just return "" rather than an error. Or of course you could continue with testing from the second character through to the second last in the loop and add an additional test for the first and last characters.
The .match() method does a regex match, so it tries to convert '+' to a regex and of course + has special meaning within a regex and doesn't match the literal. I'd suggest just using === '+' instead, though you could use .match(/\+/).
You are returning whatever value the boolean variable ends up with, which means your function is ignoring the tests on all but the second-last character in the string. You should return false immediately if you find a letter that doesn't have '+' around it.
Your question asked about "letters", but /\w/ doesn't test for a letter, it tests for letters or digits or underscores. If you actually want just letters use /[a-z]/i.
(Also there's no point assigning str = boolean, because JS function parameters are passed by value so this assignment won't affect anything outside the function.)
So:
function SimpleSymbols(str) {
for(var i=0;i<str.length;i++){
if(/[a-z]/i.test(str.charAt(i))){
if(str.charAt(i-1)!='+' || str.charAt(i+1) != '+'){
return false;
}
}
}
return true;
}
Can anyone tell me why does this not work for integers but works for characters? I really hate reg expressions since they are cryptic but will if I have too. Also I want to include the "-()" as well in the valid characters.
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
Review
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
This String "method" returns true if str is contained within itself, e.g. 'hello world'.indexOf('world') != -1would returntrue`.
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
The value of $('#textbox1').val() is already a string, so the .toString() isn't necessary here.
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
This is where it goes wrong; effectively, this executes '1234'.indexOf('0123456789') != -1; it will almost always return false unless you have a huge number like 10123456789.
What you could have done is test each character in str whether they're contained inside '0123456789', e.g. '0123456789'.indexOf(c) != -1 where c is a character in str. It can be done a lot easier though.
Solution
I know you don't like regular expressions, but they're pretty useful in these cases:
if ($("#textbox1").val().match(/^[0-9()]+$/)) {
alert("valid");
} else {
alert("not valid");
}
Explanation
[0-9()] is a character class, comprising the range 0-9 which is short for 0123456789 and the parentheses ().
[0-9()]+ matches at least one character that matches the above character class.
^[0-9()]+$ matches strings for which ALL characters match the character class; ^ and $ match the beginning and end of the string, respectively.
In the end, the whole expression is padded on both sides with /, which is the regular expression delimiter. It's short for new RegExp('^[0-9()]+$').
Assuming you are looking for a function to validate your input, considering a validChars parameter:
String.prototype.validate = function (validChars) {
var mychar;
for(var i=0; i < this.length; i++) {
if(validChars.indexOf(this[i]) == -1) { // Loop through all characters of your string.
return false; // Return false if the current character is not found in 'validChars' string.
}
}
return true;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.validate(validChars)) {
alert("Only valid characters were found! String validates!");
} else {
alert("Invalid Char found! String doesn't validate.");
}
However, This is quite a load of code for a string validation. I'd recommend looking into regexes, instead. (Jack's got a nice answer up here)
You are passing the entire list of validChars to indexOf(). You need to loop through the characters and check them one-by-one.
Demo
String.prototype.Contains = function (str) {
var mychar;
for(var i=0; i<str.length; i++)
{
mychar = this.substr(i, 1);
if(str.indexOf(mychar) == -1)
{
return false;
}
}
return this.length > 0;
};
To use this on integers, you can convert the integer to a string with String(), like this:
var myint = 33; // define integer
var strTest = String(myint); // convert to string
console.log(strTest.Contains("0123456789")); // validate against chars
I'm only guessing, but it looks like you are trying to check a phone number. One of the simple ways to change your function is to check string value with RegExp.
String.prototype.Contains = function(str) {
var reg = new RegExp("^[" + str +"]+$");
return reg.test(this);
};
But it does not check the sequence of symbols in string.
Checking phone number is more complicated, so RegExp is a good way to do this (even if you do not like it). It can look like:
String.prototype.ContainsPhone = function() {
var reg = new RegExp("^\\([0-9]{3}\\)[0-9]{3}-[0-9]{2}-[0-9]{2}$");
return reg.test(this);
};
This variant will check phones like "(123)456-78-90". It not only checks for a list of characters, but also checks their sequence in string.
Thank you all for your answers! Looks like I'll use regular expressions. I've tried all those solutions but really wanted to be able to pass in a string of validChars but instead I'll pass in a regex..
This works for words, letters, but not integers. I wanted to know why it doesn't work for integers. I wanted to be able to mimic the FilteredTextBoxExtender from the ajax control toolkit in MVC by using a custom Attribute on a textBox
How can I quickly validate if a string is alphabetic only, e.g
var str = "!";
alert(isLetter(str)); // false
var str = "a";
alert(isLetter(str)); // true
Edit : I would like to add parenthesis i.e () to an exception, so
var str = "(";
or
var str = ")";
should also return true.
Regular expression to require at least one letter, or paren, and only allow letters and paren:
function isAlphaOrParen(str) {
return /^[a-zA-Z()]+$/.test(str);
}
Modify the regexp as needed:
/^[a-zA-Z()]*$/ - also returns true for an empty string
/^[a-zA-Z()]$/ - only returns true for single characters.
/^[a-zA-Z() ]+$/ - also allows spaces
Here you go:
function isLetter(s)
{
return s.match("^[a-zA-Z\(\)]+$");
}
If memory serves this should work in javascript:
function containsOnlyLettersOrParenthesis(str)
(
return str.match(/^([a-z\(\)]+)$/i);
)
You could use Regular Expressions...
functions isLetter(str) {
return str.match("^[a-zA-Z()]+$");
}
Oops... my bad... this is wrong... it should be
functions isLetter(str) {
return "^[a-zA-Z()]+$".test(str);
}
As the other answer says... sorry