Check, if word has a same end and start in JavaScript - javascript

I'm searching for how can I check if word has a same end and start. There is my code:
JavaScript:
function Check() {
var value = document.getElementById("input").value;
if (value == startsWith(endsWith()) && value == endsWith(startsWith())) {
return alert("Yes");
} else {
return alert("No");
}
}
<input id="input" style="margin:20px;" type="text"><br>
<button id="button" onclick="Check();">Check</button>
<p id="demo" style="color:white;">Answer</p>

Just check the first and last character of the string:
if(value[0] == value[value.length-1])
{
alert('Yes');
}
else
{
alert('No');
}

Try below function.
I am comparing first character and last character of your input string.
function Check() {
var value = document.getElementById("input").value;
if (value.charAt(0) === value.charAt(value.length - 1)) {
return alert("Yes");
} else {
return alert("No");
}
}

Use str.length - 1 to get the index of the last character of the string.
function check(str) {
if (str[0] === str[str.length - 1]) {
alert('yes')
} else {
alert('no');
}
}
check('test');
check('tests');
To check first/last n characters you can do this.
function checkMore(str, amount) {
if (str[0] !== str[str.length - 1]) {
alert('no');
return;
} else if (amount !== 1) {
return checkMore(str.slice(1, str.length - 1), amount - 1);
}
alert('yes');
}
checkMore('stests', 1);
checkMore('stests', 2);
checkMore('stests', 3);
And to check the whole string (basically checking if the string is palindrome).
function checkPalindrome(str) {
if (str.length === 0 || str.length === 1) {
alert('yes');
return;
}
if (str[0] !== str[str.length - 1]) {
alert('no');
return;
}
checkPalindrome(str.slice(1, str.length - 1));
}
checkPalindrome('car');
checkPalindrome('carac');
checkPalindrome('carrac');

You can use match() or indexOf(). Both work, but both search the whole string. It is more efficient to extract the substring in the relevant place and compare it with the one you expect there:
function Check ( word ) {
return word.charAt(0) == word.charAt( word.length - 1 )
}
<button tye="button" onclick="alert( Check('Hello') )">Check 'Hello'</button>
<button tye="button" onclick="alert( Check('HelloH') )">Check 'HelloH'</button>
Of course, you might as well use a regular expression, with a smart regex engine it should be efficient as well (and your code is more concise):
function Check ( word ) {
return /^(.).*\1$|^.$/.test( word )
}
<button tye="button" onclick="alert( Check('Hello') )">Check 'Hello'</button>
<button tye="button" onclick="alert( Check('WoW') )">Check 'WoW'</button>

var value = "wow"
return (value[0] === value[value.length - 1] ? true : false)
0th index will contain starting character and value.length - 1 will contain ending character. If they are equal it will return true and false otherwise.

You can use .split('' ) to split a string by spaces, so into words. It splits it into an array, so you can compare index [0] to index [length-1]
For example
function Check(string) {
let arr = string.split(' ');
return arr[0] == arr[arr.length-1];
}

Use regex:
if (/^(.).*\1$|^.$/.test(value))
// first and last are same letter

Related

Palindrome Check in javascript but with while loop

I am trying to make a palindrome checker with the condition of having to use a while loop.
It's giving me a right headache!
it returns isPalindrome as false every time even if the word is a palindrome.
let word = prompt('Please Enter a word')
let reverse = word.split('').reverse().join('').toLowerCase();
i = 0
final = word.length
let isPalindrome = false
while (i < word.length) {
if(word[i] == reverse[i])
i++
if(i = word.length)
break;
else if (i !== word.length)
break;
}
if (i == word.length) {
isPalindrome == true
}
else if (true) {
isPalindrome == false
}
if (isPalindrome == true) {
window.alert('Your word is a palindrome')
}
else if (isPalindrome == false) {
window.alert('Your word is not a palindrome')
}
I have tried messing around with the == signs and changing the break;
it used to return as always palindrome, but now it always returns as not a palindrome
The idea is to compare the word with the reverse version of it and check every index to see if it matches.
If they all match the word is a palindrome (racecar && racecar)
If they do not match it is not (racer && recar)
The program should output the result
Many thanks!
Alternative: nibble off letters of the word from both sides and compare them until either there's one letter left (is palindrome) or they don't match (no palindrome):
const isPalindrome = word => {
const letters = word.toLowerCase().split("");
while (letters.length > 1) {
if (letters.shift() !== letters.pop()) {
// not a palindrome: break the loop
// by returning false
return false;
};
}
return true;
}
console.log(`racecar ${isPalindrome(`racecar`)}`);
console.log(`rotator ${isPalindrome(`rotator`)}`);
console.log(`carrace ${isPalindrome(`carrace`)}`);
console.log(`rotonda ${isPalindrome(`rotonda`)}`);

Recursively add to strings in JS

I'm tackling a recursion problem that returns a string of "hi"'s where the first "hi" has a capital H and the string ends with an exclamation point. I have the code below so far but I'm not sure how to prevent subsequent occurrences of "hi" having a capital H. Any guidance would be welcome.
function greeting(n) {
if (n === 0) {
return "";
} else if (n === 1) {
return "Hi!"
} else {
return `${'Hi' + greeting(n - 1)}`
}
}
console.log(greeting(3)) // should return Hihihi!
console.log(greeting(5)) // should return Hihihihihi!
One way to work around your problem is to pass a flag to the function which indicates whether this is the first call, and only in that case capitalise the hi. Note that you can simplify the code slightly by returning a ! when n == 0; then you don't need to special case n == 1:
function greeting (n, first = true) {
if (n === 0) {
return "!";
}
else {
return `${(first ? 'Hi' : 'hi') + greeting(n - 1, false)}`
}
}
console.log(greeting(3)) // should return Hihihi!
console.log(greeting(5)) // should return Hihihihihi!
Just a .toLowerCase() is missing in your code.
`${'Hi' + greeting(n - 1).toLowerCase()}`
You don't need the n === 1 step.
function greeting(n) {
if (n === 0) {
return "!";
} else {
return `${'Hi' + greeting(n - 1).toLowerCase()}`
//------------------------------^^^^^^^^^^^^^^
}
}
console.log(greeting(3)) // should return Hihihi!
console.log(greeting(5)) // should return Hihihihihi!

Recursive palindrome check with JavaScript

I am trying to find out whether a string is a palindrome by recursion using javascript. But I can't figure out what I am missing in the code.
var firstCharacter = function(str) {
return str.slice(0, 1);
};
var lastCharacter = function(str) {
return str.slice(-1);
};
var middleCharacters = function(str) {
return str.slice(1, -1);
};
var isPalindrome = function(str) {
if(str.length < 2) {
return true;
} else {
if(firstCharacter(str) == lastCharacter(str)) {
isPalindrome(middleCharacters(str));
} else return false;
}
};
var checkPalindrome = function(str) {
console.log("Is this word a palindrome? " + str);
console.log(isPalindrome(str));
};
checkPalindrome("a");
//Program.assertEqual(isPalindrome("a"), true);
checkPalindrome("matom");
//Program.assertEqual(isPalindrome("motor"), false);
checkPalindrome("rotor");
//Program.assertEqual(isPalindrome("rotor"), true);
For sure something is wrong with the recursive call. I would love to have your help. Thanks. I am attaching the output of my code.
Here is another recursive palindrome.
function checkPalindrome(str){
if(str.length === 1) return true;
if(str.length === 2) return str[0] === str[1];
if(str[0] === str.slice(-1)) return checkPalindrome(str.slice(1,-1))
return false;
}
console.log(checkPalindrome('a')) // true
console.log(checkPalindrome('matom')) // false
console.log(checkPalindrome('rotor')) // true
You defined isPalindrome() to return a value, so if you call it yourself, recursively or otherwise, you need to deal with that return value. Also, your if ... else logic is too complicated, simplify:
var isPalindrome = function(str) {
if (str.length < 2) {
return true;
}
if (firstCharacter(str) == lastCharacter(str)) {
return isPalindrome(middleCharacters(str));
}
return false;
};
const isPalindrome = str => {
const strLen = str.length;
if (strLen < 2) return true;
if (str[0] === str[strLen - 1]) {
return isPalindrome( str.slice(1, strLen - 1) );
}
return false;
};
console.log(isPalindrome('madam'));
Using slice creates an array - if you want to compare the first and last char, you will need to extract the value from the array before applying == -
var firstCharacter = function(str) {
return str.slice(0, 1)[0] // <-- get the first element of the slice
}
var lastCharacter = function(str) {
return str.slice(-1)[0] // <-- get the first element of the slice
}
Here's another recursive solution that uses parameters l (left) and r (right) to check the string using indexes (rather than creating intermediate values with slice) -
const palindrome = (s = "", l = 0, r = s.length - 1) =>
r - l < 2
? true
: s[l] === s[r] && palindrome (s, l + 1, r - 1)
console.log
( palindrome ("motor") // false
, palindrome ("rotor") // true
, palindrome ("racecar") // true
, palindrome ("wow") // true
, palindrome ("i") // true
)
And here's a mutually recursive definition. It's wasteful but it has an elegant form nonetheless -
const pal = ([ s, ...more ]) =>
more.length === 0 || pal2 (more.reverse(), s)
const pal2 = ([ s, ...more ], q) =>
s === q && pal (more.reverse())
console.log
( pal ("motor") // false
, pal ("rotor") // true
, pal ("racecar") // true
, pal ("wow") // true
, pal ("i") // true
)
Here is another way to recursively check for a palindrome in JS:
function isPalindrome(str){
if (str[0] === str[str.length - 1] && str.length > 1) {
isPalindrome(str.substring(1, str.length -1))
return true
}else{
return false
}
}
Here's a simple answer for ya. Basically we are comparing the first character to last character and acting accordingly.
const isPalindrome = str => {
if (str.length <= 1) return true;
if (str[0] !== str[str.length - 1]) return false;
return isPalindrome(str.slice(1,-1))
}
const isPalindrome = str => {
// base case
if(str.length === 1) return true;
if(str.length === 2) return str[0] === str[1];
if(str[0] === str[str.length - 1]) {
return isPalindrome(str.slice(1, -1))
}
return false;
}
you can use recursion
base case
we have a base case (the simple case) if the string is one char we simply returns true.
if it has two chars we check if the first char is identical to the second and we return true if they are.
recursive case
if it is more than two chars we check if the first and last chars are identical or not if they are not we simply return false
but if they are identical so we now want to do the same thing with other chars so we call the same function with the same string but removing the first and last chars because we already know that they are identical and we keep going until we reach the base case.
hope this be useful
some tests
isPalindrome('p') // true
isPalindrome('po') // false
isPalindrome('pp') // true
isPalindrome('pop') //true
What's about this solution ?
function isPalindrome(str){
if (str.length > 3) return isPalindrome(str.substring(1, str.length-1));
return str[0] === str[str.length-1];
}
My simple implementation for a recursive palindrome check, in 2022:
function isPalindrome(str) {
if (!str.length || str.length === 1) return true;
return str[0] === str.at(-1) ? isPalindrome(str.substr(1, str.length - 2)) : false;
}
console.log(isPalindrome('catotac'));
Iterations breakdown:
// 1st iteration:
isPalindrome('catotac');
//2nd iteration
isPalindrome('atota');
//3rd
isPalindrome('tot');
// 4th iteration
isPalindrome('o'); // true

jQuery function for check textbox

I’d like use jquery function that validate a input field. This input field must be used for entering 11 digit numbers that start with 0.
I tried some function but doesn’t work!
function check(mob) {
var firstnum = mob.substring(1);
alert(firstnum);
if (firstnum != "0" || mob.lenght != 11)
return false;
else
return true;
}
function check(mob) {
return mob.substring(0, 1) == '0' && mob.length == 11;
}
String Method Reference
If you want to check is it 11 digit, you should use RegExp
function check(mob) {
return mob.match(/^0\d{10}$/) != null;
}
You need to use .charAt(0) to get the first character of a string. .substring(1) will return the rest of the string minus the first character.
"01234567890".substring(1) = "1234567890"
"01234567890".charAt(0) = "0"
"01234567890".length = 11 (assuming that you have spelled "length" correctly in your code)
Edit: Since you also need to check for digits, you could use a regular expression to verify this (although the whole check could also be done with a regex)
The completed function could therefore be simplified to just:
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && /^\d+$/.test(mobileNumber);
}
Or without the regex
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && !isNaN(mobileNumber);
}
if (firstnum >= 1 || mob.lenght <= 11) //lenght spell wrong
change to
if (firstnum >= 1 || mob.length<= 11)
you can give it a try
function check(mob) {
var num = parseInt(mob);
if (mob+'' == '0'+num && mob.length == 11)
return true;
else
return false;
}
here what I am doing is that parseInt will give you exact same number without 0 if all characters are numbers, so in the condition I am just adding 0 in starting and checking with mobile number , it will do 2 validation in once , all are number starts with 0 and next validation is for length
Try using a simple regex as below
function check(mob) {
return /^0\d{10}$/.test(mob)
}
function check(mob) {
if(!isNaN(mob)){ // or use parseInt
var firstnum = mob.charAt(0);
alert(firstnum);
if (firstnum != "0" || mob.length != 11) {
return false;
} else {
return true;
}
}
}

JavaScript endWith()

I'm having trouble getting the following to work
if(str.endsWith('+')
{
alert("ends in plus sign")
}
How do I escape the plus sign? I've tried /\ +/ but it doesn't work.
There is no endsWith method in JavaScript, so instead use:
if (str.substr(-1) === "+") {
alert("ends in plus sign")
}
The Javascript String type doesn't have an endsWith function, but you can give it one if you like:
if (!String.prototype.endsWith) {
(function() {
String.prototype.endsWith = String_endsWith;
function String_endsWith(sub) {
return this.length >= sub.length && this.substring(this.length - sub.length) == sub;
}
})();
}
Or if you don't mind unnamed functions:
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(sub) {
return this.length >= sub.length && this.substring(this.length - sub.length) == sub;
};
}
Either way, you could then do:
if ("foo".endsWith("oo")) {
// ...
}
String.prototype.endswith= function(c){
if(!c) return this.charAt(this.length - 1);
else{
if(typeof c== "string") c= RegExp(c + "$");
return c.test(this);
}
}
var s='Tell me more:', s2='Tell me about part 2:';
s.endsWith() // returns ':';
s.endsWIth(':') // returns true, last character is ':';
s2.endsWIth(/\d:?/) // returns true. string ends with a digit and a (possible) colon
Use RegExp:
a = "csadda+"
if (a.match(/.*\+$/)) {
alert("Ends");
}

Categories

Resources