Check if a string is palindrome using only pure javascript - javascript

I have this function
function palindrome(str){
var myStr = "";
for (var index = str.length -1 ; index >=0; index--) {
myStr += str[index]
}
var res = myStr == str ? true : false;
return res;
}
It works with a single word , but if i checked such as "I did, did I?" , it don't works. How i can check is without using replace , join , reverse , etc... Only pure js . Thanks very much .

This is how i do it, run the loop both incremental and decremental fashion at the same time
function palindrome() {
var str = "dd dd";
var Ispalindrome = true;
for (var i = 0, j = str.length - 1; i < str.length && j >= 0; i++, j--) {
if (str[i] !== str[j]) {
Ispalindrome = false;
}
}
alert(Ispalindrome);
return Ispalindrome;
}
//Invoked
palindrome()

Related

How do you iterate over an array every x spots and replace with letter?

/Write a function called weave that accepts an input string and number. The function should return the string with every xth character replaced with an 'x'./
function weave(word,numSkip) {
let myString = word.split("");
numSkip -= 1;
for(let i = 0; i < myString.length; i++)
{
numSkip += numSkip;
myString[numSkip] = "x";
}
let newString = myString.join();
console.log(newString);
}
weave("weave",2);
I keep getting an infinite loop. I believe the answer I am looking for is "wxaxe".
Here's another solution, incrementing the for loop by the numToSkip parameter.
function weave(word, numToSkip) {
let letters = word.split("");
for (let i=numToSkip - 1; i < letters.length; i = i + numToSkip) {
letters[i] = "x"
}
return letters.join("");
}
Well you need to test each loop to check if it's a skip or not. Something as simple as the following will do:
function weave(word,numSkip) {
var arr = word.split("");
for(var i = 0; i < arr.length; i++)
{
if((i+1) % numSkip == 0) {
arr[i] = "x";
}
}
return arr.join("");
}
Here is a working example
Alternatively, you could use the map function:
function weave(word, numSkip) {
var arr = word.split("");
arr = arr.map(function(letter, index) {
return (index + 1) % numSkip ? letter : 'x';
});
return arr.join("");
}
Here is a working example
Here is a more re-usable function that allows specifying the character used for substitution:
function weave(input, skip, substitute) {
return input.split("").map(function(letter, index) {
return (index + 1) % skip ? letter : substitute;
}).join("");
}
Called like:
var result = weave('weave', 2, 'x');
Here is a working example
You dont need an array, string concatenation will do it, as well as the modulo operator:
function weave(str,x){
var result = "";
for(var i = 0; i < str.length; i++){
result += (i && (i+1)%x === 0)?"x":str[i];
}
return result;
}
With arrays:
const weave = (str,x) => str.split("").map((c,i)=>(i&&!((i+1)%x))?"x":c).join("");
You're getting your word greater in your loop every time, so your loop is infinite.
Try something like this :
for(let k = 1; k <= myString.length; k++)
{
if(k % numSkip == 0){
myString[k-1]='x';
}
}
Looking at what you have, I believe the reason you are getting an error is because the way you update numSkip, it eventually becomes larger than
myString.length. In my code snippet, I make i increment by numSkip which prevents the loop from ever executing when i is greater than myString.length. Please feel free to ask questions, and I will do my best to clarify!
JSFiddle of my solution (view the developer console to see the output.
function weave(word,numSkip) {
let myString = word.split("");
for(let i = numSkip - 1; i < myString.length; i += numSkip)
{
myString[i] = "x";
}
let newString = myString.join();
console.log(newString);
}
weave("weave",2);
Strings are immutable, you need a new string for the result and concat the actual character or the replacement.
function weave(word, numSkip) {
var i, result = '';
for (i = 0; i < word.length; i++) {
result += (i + 1) % numSkip ? word[i] : 'x';
}
return result;
}
console.log(weave("weave", 2));
console.log(weave("abcd efgh ijkl m", 5));
You can do this with fewer lines of code:
function weave(word, numSkip) {
word = word.split("");
for (i = 0; i < word.length; i++) {
word[i] = ((i + 1) % numSkip == 0) ? "x" : word[i];
}
return word.join("");
}
var result = weave("weave", 2);
console.log(result);

Identify palindromes in a sentence

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/

javascript toLowerCase() function returns different string

console.log("HİNDİ".toLocaleLowerCase() == "hindi");
console.log("HİNDİ" == "hindi");
console.log("HİNDİ".toLowerCase());
console.log("HİNDİ".toLocaleLowerCase())
console.log("HİNDİ".toLowerCase())
I am building a search functionality but i come across a thing:
"HİNDİ".toLocaleLowerCase() // "hindi"
"hindi" == "HİNDİ".toLocaleLowerCase() //false
What the heck is going on here?
Solution:
#pmrotule's answer seems to work:
function to_lower(s)
{
var n = "";
for (var i = 0; i < s.length; i++) // do it for one character at a time
{
var c = s[i].toLowerCase();
// call replace() only if the character has a length > 1
// after toLowerCase()
n += c.length > 1 ? c[0].replace(/[^ -~]/g,'') : c;
}
return n;
}
Thanks,
It is a problem of string format. toLocaleLowerCase is meant for human-readable display only. However, there is still a trick you can do:
if ("hindi" == "HİNDİ".toLowerCase().replace(/[^ -~]/g,''))
{
alert("It works!");
}
EDIT
If you want to make it works with all special characters:
function to_lower(s)
{
var n = "";
for (var i = 0; i < s.length; i++) // do it for one character at a time
{
var c = s[i].toLowerCase();
// call replace() only if the character has a length > 1
// after toLowerCase()
n += c.length > 1 ? c.replace(/[^ -~]/g,'') : c;
}
return n;
}
console.log("gök" == to_lower("GÖK"));
console.log("hindi" == to_lower("HİNDİ"));
function to_low(s) // shorter version
{
var n = "";
for (var i = 0; i < s.length; i++)
{ n += s[i].toLowerCase()[0]; }
return n;
}
console.log("hindi" == to_low("HİNDİ"));
The problem is that your character İ is composed by 2 characters.
You have the I and then the 'dot' at the top (UTF-8 decimal code: 775).
Try this:
"HİNDİ".toLocaleLowerCase().split('').map((_,v)=>console.log(_.charCodeAt(0)))
Compare it with this:
"hindi".toLocaleLowerCase().split('').map((_,v)=>console.log(_.charCodeAt(0)))

Palindrome function returns true when word isn't a palindrome

Could someone be kind enough to tell me why "almostomla" returns true in my code.
I have searched and have seen there are simpler versions but im so deep into this code now i need to make it work if at all possible.
Please excuse the terrible variable names, i was frustrated.
function palindrome(str) {
str = str.toLowerCase();
str = str.replace(/ /g, '').replace(/\./g, '').replace(/,/g, '');
for (var i = 0; i < str.length / 2; i++) {
for (var j = str.length - 1; j > str.length / 2 - 1; j--) {
var iDntKnow = str.charAt(i);
var iDntKnowEither = str.charAt(j);
if (iDntKnow === iDntKnowEither) {
return true;
} else {
return false;
}
}
}
}
Appreciate all answers.
While I can understand the frustration of wanting to make something work if you have put time into it, there is also something to be said for starting from the drawing board and not driving yourself crazy. The main problem I see with your code is that you have two loops when you only need one. The second loop is actually sabotaging you. I would suggest running a debugger (type "debugger" into your code and run) to see why.
I believe this is what you are trying to accomplish:
var palindrome = function(str) {
// Put any additional string preprocessing here.
for(var i = 0; i < str.length/2; i++) {
var j = str.length-i-1;
if (str[i] != str[j]) {
return false;
}
}
return true;
}
In this way you are comparing each mirrored element in the string to confirm if the string is a palindrome.
Your question seems to be answered by now.
If performance isn't an issue, why not just use this?
function palindrome(str) {
str = str.toLowerCase();
return (str.split().reverse().join() === str)
}
It splits the string into an array, reverses that and joins it back together. The result is compared to the original string.
You can only know if it's NOT a palindrome in each iteration.
Also, why using nested loops?
function palindrome(str) {
str = str.toLowerCase();
str = str.replace(/ /g, '').replace(/\./g, '').replace(/,/g, '');
for (var i = 0; i < str.length / 2; i++) {
if (str.charAt(i) !== str.charAt(str.length - i - 1)) {
return false;
}
}
return true;
}
This works:
function palindrome(string) {
string = string.toLowerCase();
for (var i = 0; i < Math.ceil(str.length/2); i++) {
var character1 = string.charAt(i);
var character2 = string.charAt(string.length-1-i);
if (character1 !== character2) {
return false;
}
}
return true;
}
Here is a version that omits spaces and commas:
var removeLetterFromString = function(string,letterPos){
var returnString = "";
for(var i = 0; i < string.length; i++){
if(i!==letterPos){
returnString=returnString+string.charAt(i);
}
}
return returnString;
};
var palindrome = function(string) {
string = string.toLowerCase();
var stringCheck="";
var recheck = true;
while(recheck){
recheck=false;
for(var i = 0; i < string.length; i ++){
if(string.charAt(i)===" "||string.charAt(i)===","){
string=removeLetterFromString(string,i);
}
}
for(var i = 0; i < string.length; i ++){
if(string.charAt(i)===" "||string.charAt(i)===","){
recheck=true;
}
}
}
if(string.length===0){
return false;
}
for (var i = 0; i < Math.ceil(string.length/2); i++) {
var j = string.length-1-i;
var character1 = string.charAt(i);
var character2 = string.charAt(j);
if (character1 !== character2) {
return false;
}
}
return true;
};

Insert dashes into a number

Any ideas on the following? I want to input a number into a function and insert dashes "-" between the odd digits. So 4567897 would become "456789-7". What I have so far is to convert the number into a string and then an array, then look for two odd numbers in a row and use the .splice() method to add the dashes where appropriate. It does not work and I figure I may not be on the right track anyway, and that there has to be a simpler solution.
function DashInsert(num) {
var numArr = num.toString().split('');
for (var i = 0; i < numArr.length; i++){
if (numArr[i]%2 != 0){
if (numArr[i+1]%2 != 0) {
numArr.splice(i, 0, "-");
}
}
}
return numArr;
}
The problem is you're changing the thing you're iterating over. If instead you maintain a separate output and input...
function insertDashes(num) {
var inStr = String(num);
var outStr = inStr[0], ii;
for (ii = 1; ii < inStr.length; ii++) {
if (inStr[ii-1] % 2 !== 0 && inStr[ii] % 2 !== 0) {
outStr += '-';
}
outStr += inStr[ii];
}
return outStr;
}
You can try using regular expressions
'4567897'.replace(/([13579])(?=[13579])/g, '$1-')
Regex Explained
So, we find an odd number (([13579]) is a capturing group meaning we can use it as a reference in the replacement $1) ensure that it is followed by another odd number in the non-capturing positive lookahead ((?=[13579])) and replace the matched odd number adding the - prefix
Here is the function to do it:
function dashes(number){
var numString = '';
var numArr = number.toString().split('');
console.log(numArr);
for(i = 0; i < numArr.length; i++){
if(numArr[i] % 2 === 1 && numArr[i+1] % 2 === 1){
numString += numArr[i] + '-';
}else{
numString += numArr[i];
}
}
console.log(numString);
}
dashes(456379);
Tested and everything.
Edit: OrangeDog's answer was posted earlier (by nearly a full half hour), I just wanted to make an answer which uses your code since you're almost there.
Using another array instead of splicing into one you were looping through (this happens to return a string using join):
var num = 4567897;
function DashInsert(num) {
var numArr = num.toString().split('');
var len = numArr.length;
var final = [];
for (var i = 0; i < len; i++){
final.push(numArr[i]);
if (numArr[i]%2 != 0){
if (i+1 < len && numArr[i+1]%2 != 0) {
final.push("-")
}
}
}
return final.join("");
}
alert(DashInsert(num));
function dashInsert(str) {
var arrayNumbers = str.split("");
var newString = "";
for (var i = 0; i < arrayNumbers.length; i++){
if(arrayNumbers[i] % 2 === 1 && arrayNumbers[i + 1] % 2 === 1){
newString = newString + arrayNumbers[i] + "-";
} else {
newString = newString + arrayNumbers[i];
}
}
return newString;
}
var result = dashInsert("3453246");
console.log(result);

Categories

Resources