Reverse string to find palindromes in JavaScript - javascript

I have two strings. The first is normal string, the second I want to be a reversed string like first one, but in the console I didn't get the look of like first one listed by commas. How can I fix that ?
Normal string -
Revered string -
window.onload = function(){
inputBox = document.getElementById("myText");
btn = document.getElementById('sub');
btn.addEventListener("click",function(event){
event.preventDefault();
findPalindromes(inputBox.value);
});
str = inputBox.value;
function findPalindromes(str) {
var words = str.split(" ");
for (var i = 0; i < words.length - 1; i++) {
words[i] += " ";
}
console.log(words);
var newString = "";
for (var i = words.length - 1; i >= 0; i--) {
newString += words[i];
}
console.log(newString);
}
}

If you really just want to find out if a string is a palindrome, you can do something as simple as this:
function isPalindrome(str) {
return str.toLowerCase() === str.toLowerCase().split('').reverse().join('');
}

The first for loop is not necessary. You do not need to concatenate a space character " " to the element of the array, where the variable assignment i
var i = 0;
and condition
i < words.length - 1;
stops before reaching last element of array.
var newString = "";
for (var i = words.length - 1; i >= 0; i--) {
newString += words[i] + " ";
}
console.log(newString);

In your "normal" string example, you're printing words to the console. Let's first look at what words is: var words = str.split(" ");
The String.split() function returns an array of strings. So your "normal" string is actually an array of strings (The brackets [] and comma separated strings in the console output indicate this).
In the second example, you're logging newString. Let's look at where it comes from: var newString = "";
newString is a String. If you want it to be an array of strings like words, you would declare it with var newString = [];. Arrays do not support += so newString += words[i]; would become newString.push(words[i]);
The above explains how to get newString to behave like words, the code you've written is not looking for a palindrome word, but rather a palindrome sentence: "Bob is Bob" is not a palindrome (reversed it is "boB si boB") but it could be a Palindrome sentence (if such a thing exists).

Thanks to all, I wrote this solution for the problem. I hope this is the right answer.
window.onload = function(){
inputBox = document.getElementById("myText");
btn = document.getElementById('sub');
btn.addEventListener("click",function(event){
event.preventDefault();
findPalindromes(inputBox.value);
});
str = inputBox.value;
function findPalindromes(str) {
var words = str.split(" "),
newString = [];
for (var i = 0; i < words.length - 1; i++) {
if ((words[i] === words[i].split('').reverse().join('')) === true) {
newString.push(words[i]);
}
}
console.log(newString);
}
}

var words = " ";
function reverse_arr(arr){
var i = arr.length - 1;
while(i >= 0){
words += a[i] + " ";
i--;
}
return words;
}

Related

How to reverse word by word in a string using javascript?

I'm writing the logic for reverse word by word in string javascript.
But I'm thinking my code is more lengthy so, I'm looking for good answer.
Ex :- I/p- Hi how are you // o/p- iH woh era uoy
function ReverseString(val) {
var op = "",
iCount = -1;
for (let i = 0; i <= val.length; i++) {
if (val[i] != " " && i != val.length)
continue;
for (let j = i - 1; j > iCount; j--)
op += val[j];
if (i != val.length)
op += " ";
iCount = i;
}
return op;
}
console.log(ReverseString("Hi how are you"));
One way would be to split the string by whitespace to have an array of words, then reverse those words within the array using map(), like this:
function ReverseString(val) {
return val.split(/\s/g).map(w => w.split('').reverse().join('')).join(' ');
}
console.log(ReverseString("Hi how are you"));
Your solution.
<script>
rev=(val)=>{
return val.split("").reverse().join("").split(" ").reverse().join(" ")
}
console.log(rev('Hi how are you'))
</script>
A way to do this is to seperate you words in an array using split()
Then for each word, split the letters and use the reverse function and re-join them.
At least, re-join the word
const str = "Hi how are you";
let str_reversed = str.split(' ');// put each word in an array
str_reversed = str_reversed.map(word => word.split('').reverse().join('')); // for each word, we put each letter in array, reverse them and then re-join them
str_reversed = str_reversed.join(' '); // rejoin the word
console.log(str_reversed);
A one line solution to reverse each word maintaining the order:
var original = 'Hi how are you';
var reversed = original.split("").reverse().join("").split(" ").reverse().join(" ")
o/p: "iH woh era uoy"
let str = 'Hi how are you';
let reverse = str
.split("")
.reverse()
.join("")
.split(" ")
.reverse()
.join(" ")
);

What is wrong with the logic of my character changing function?

I've tried to create a character changing function for strings, it suppose to change all the "-" to "_", and it only does it for the first character and leaves the rest. If someone could explain it would be grate.
function kebabToSnake(str) {
var idNum = str.length;
for(var i = 0; i <= idNum; i++) {
var nStr = str.replace("-", "_");
}
return nStr;
}
var nStr = str.replace("-", "_");
So, on each iteration, you're replacing the first found - character in the original string, not the string that you've already replaced characters from already. You can either call .replace on just one variable that you reassign:
function kebabToSnake(str) {
var idNum = str.length;
for(var i = 0; i < idNum; i++) {
str = str.replace("-", "_");
}
return str;
}
console.log(kebabToSnake('ab-cd-ef'));
(note that you should iterate from 0 to str.length - 1, not from 0 to str.length)
Or, much, much more elegantly, use a global regular expression:
function kebabToSnake(str) {
return str.replace(/-/g, '_');
}
console.log(kebabToSnake('ab-cd-ef'));

Why is my for loop using push inside a function not working?

I am trying to pass a phrase through a function so that every first letter is capitalized and everything else is lower case. I have the following function:
function titleCase(str) {
var array = [];
for (var i = 0; i <= str.length; i++) {
str = str.split(' ');
str = str[i].toLowerCase();
str = str.charAt(0).toUpperCase() + str.substr(1, str.length);
array = array.push(str);
return array.push(str);
}
}
titleCase("SenTencE TesT");
Without the for loop the function works and will lowercase everything and then capitalize the first letter of each word.
[EDIT]
A lot of ways to do it, but try this...
function titleCase(string) {
var array = string.split(' ');
var newString = '';
for (var i = 0; i <= array.length-1; i++) {
array[i] = array[i].toLowerCase();
array[i] = array[i].charAt(0).toUpperCase() + array[i].substr(1, array[i].length);
newString += array[i] + ' ';
};
return newString.trim();
};
console.log( titleCase("SenTencE TesT") );
1) Don't name your variable array, that is a JavaScript reserved word, you can use "arr" for example.
2) In your code you are splitting the sentence in to an array of words but you are only applying the toLowerCase to the first word.
3) There's a much cleaner way to achieve the result you want:
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
console.log( capitalize("sentence TesT") );
Hope it helps.

How to repeat characters in a string in javascript by using slice function?

Can anyone shed light on how to frame a javascript function with two parameters: string and character, and only by using the slice method, return the number of times "a" appears in "lava"?
without slice method
var fruits= "lavaaagg";
var count=0;
for(var i=0;i<fruits.length;i++){
if(fruits[i]!='a')
count++;
}
console.log(fruits.length-count);
I'm not sure why you need the slice method. The slice method isn't for searching substrings (or characters in your case), it extracts a substring.
This should work fine:
function howManyCharInStr(str, char) {
return str.split(char).length - 1;
}
Step-by-step explanation:
str.split(char)
Creates an array of str substrings, using char as a separator. For example:
'fooXbazXbar'.split('X')
// Evaluates to ['foo', 'baz', 'bar']
'lorem ipsum dolor'.split('m')
// Evaluates to ['lore', ' ipsu', ' dolor']
Notice how the array returned has a length of n+1 where n is the number of separators there were. So use
str.split(char).length - 1;
to get the desired result.
For getting number of charecters count
<script type="text/javascript">
function FindResults() {
var firstvariable= document.getElementById('v1');
var secondvariable = document.getElementById('v2');
var rslt = GetCharecterCount(firstvariable, secondvariable );
}
function GetCharecterCount(var yourstring,var charecter){
var matchesCount = yourstring.split(charecter).length - 1;
}
</script>
using slice method
var arr = yourstring.split(charecter);
for( var i = 0, len = arr.length; i < len; i++ ) {
var idx = yourstring.indexOf( arr[i] );
arr[i] = pos = (pos + idx);
str = str.slice(idx);
}
var x= arr.length-1;
example http://jsfiddle.net/rWJ5x/2/
Using slice method
function logic(str,char){
var count = 0;
for(var i = 0; i < str.length; i++){
if(str.slice(i,i+1) == char){
count++;
}
}
return count;
};
console.log( "count : " + logic("lava","a") );
repeat last character of sting n number of times..
function modifyLast(str, n) {
var newstr = str.slice(-1)
var newlaststr = newstr.repeat(n-1)
var concatstring = str.concat(newlaststr);
return concatstring;
}
//modifyLast();
console.log(modifyLast("Hellodsdsds", 3))

How can I avoid counting triplicates as pairs while iterating through an ordered series of letters within an array?

I wrote a simple program to analyze a string to find the word with the greatest amount of duplicate letters within it. It essentially takes a given string, breaks it up into an array of separated words, and then breaks up each separate word into alphabetically sorted groups of individual letters (which are then compared as prev and next, 2 at a time, as the containing array is iterated through). Any two adjacent and matching values found adds one tally to the hash-file next to the word in question, and the word with the most tallied pairs of duplicate letters is returned at the end as greatest. No matching pairs found in any word returns -1. This is what it's supposed to do.
Below, I've run into a problem: If I don't use a REGEXP to replace one of my matched characters, then my code gives false positives as it will count triplicates (eg, "EEE"), as two separate pairs, (eg, "EEE" = "EE & EE", instead of being viewed as "EE, E"). However, if I DO use the REGEXP below to prevent triplicate counts, then doing so breaks my loop mid-stride, and skips to the next word. Is there no way to make this way work? If not, would it be better to employ a REGEXP which deletes all chars EXCEPT the duplicate characters in question, and then perhaps I could divide the .length of each word by 2 to get the number of pairs remaining? Any ideas as to how to solve this would greatly help.
var str = "Helloo aplpplpp pie";
//var str = "no repting letrs";
//var str = "ceoderbyte";
function LetterCountI(str) {
var input = str.split(" ");
console.log(input);
console.log("\n")
var hashObject = {};
var word = "";
var count = 0;
for(var i = 0; i<input.length; i++) {
var currentItem = input[i];
var currentWordIntoChars = currentItem.split("").sort();
console.log(currentWordIntoChars);
var counter = 0;
for(var j=1; j<currentWordIntoChars.length; j++) {
console.log(currentWordIntoChars[j-1] + "=currentChar j-1");
console.log(currentWordIntoChars[j] + "=prev j");
console.log("-");
var final = currentItem;
if(currentWordIntoChars[j-1] == currentWordIntoChars[j]) {
counter++;
hashObject[final] = counter;
//currentWordIntoChars = currentWordIntoChars[j-1].replace(/[a-z]/gi, String.fromCharCode(currentItem.charCodeAt(0)+1));
//HERE REPLACE j-1 with random# or something
//to avoid 3 in a row being counted as 2 pair
//OR use regexp to remove all but pairs, and
//then divide .length/2 to get pairs.
console.log(counter + " === # total char pairs");
}
if(count<hashObject[currentItem]) {
word = final;
count = hashObject[currentItem];
}
}
}
console.log(hashObject);
console.log("\n");
for (var o in hashObject) if (o) return word;
return -1;
}
console.log(LetterCountI(str));
An other way to do it, consists to replace duplicate characters in a sorted word:
var str = "Helloo aplpplpp pie";
function LetterCountI(str) {
var input = str.split(" ");
var count = 0;
var result = -1;
for(var i = 0; i<input.length; i++) {
var nb = 0;
var sortedItem = input[i].split("").sort().join("");
sortedItem.replace(/(.)\1/g, function (_) { nb++ });
if (nb > count) {
count = nb;
result = input[i];
}
}
return result;
}
console.log(LetterCountI(str));
Notes: The replace method is only a way to increment nb using a callback function. You can do the same using the match method and counting results.
if two words have the same number of duplicates, the first word will be returned by default. You can easily change this behaviour with the condition of the if statement.
Whenever you find a match within a word, increment j by 1 to skip comparing the next letter.
var str = "Helloo aplpplpp pie";
//var str = "no repting letrs";
//var str = "ceoderbyte";
function LetterCountI(str)
{
var input = str.split(" ");
console.log(input);
console.log("\n")
var hashObject = {};
var word = "";
var count = 0;
for(var i = 0; i<input.length; i++)
{
var currentItem = input[i];
var currentWordIntoChars = currentItem.split("").sort();
console.log(currentWordIntoChars);
var counter = 0;
for(var j=1; j<currentWordIntoChars.length; j++)
{
console.log(currentWordIntoChars[j-1] + "=currentChar j-1");
console.log(currentWordIntoChars[j] + "=prev j");
console.log("-");
var final = currentItem;
if(currentWordIntoChars[j-1] == currentWordIntoChars[j])
{
counter++;
hashObject[final] = counter;
j++; // ADD HERE
console.log(counter + " === # total char pairs");
}
if(count<hashObject[currentItem])
{
word = final;
count = hashObject[currentItem];
}
}
}
console.log(hashObject);
console.log("\n");
for (var o in hashObject) if (o) return word;
return -1;
}
console.log(LetterCountI(str));

Categories

Resources