Sorry for the awkward formatting. I wrote this palindrome checking program and can't figure out why it always returns true. The 'word'refers to an intake through html and so does 'reportIfPalindrome'. Values are intaked and displayed so there is no problem with the html. Any help is appreciated
const wordBox = document.getElementById('word');
wordBox.addEventListener('input', checkIfPalindrome);
function checkIfPalindrome() {
const word = wordBox.value;
const allCaps = word === word.toUpperCase();
const outsideTrim = allCaps === word.trim();
let completelyTrimmed = "";
let individualCharacter = "";
for(x=0; x<outsideTrim.length; x++)
{
individualCharacter = outsideTrim.substring(x, x+1)
completelyTrimmed+= individualCharacter === " "? "": individualCharacter;
}
let reverseString = ""
for (x=completelyTrimmed.length-1; x>=0; x--){
reverseString = completelyTrimmed.substring(x, x+1);
}
let result = completelyTrimmed===reverseString;
document.getElementById('reportIfPalindrome').innerHTML = result;
}
There are quite a few flaws in your code. First, you are storing booleans for the variables where you seemingly intend to store the capitalized and trimmed words. Secondly, you are not running the loop with the right boundary conditions. See the updated snippet below.
checkIfPalindrome();
function checkIfPalindrome() {
const word = "aBa";
const allCaps = word.toUpperCase();
const outsideTrim = allCaps.trim();
let completelyTrimmed = "";
let individualCharacter = "";
for(x=0; x<outsideTrim.length; x++)
{
individualCharacter = outsideTrim.substring(x, x+1)
completelyTrimmed+= individualCharacter === " "? "": individualCharacter;
}
let reverseString = ""
for (x=completelyTrimmed.length-1; x>=0; x--){
reverseString = reverseString + completelyTrimmed.substring(x, x+1);
}
let result = completelyTrimmed===reverseString;
//document.getElementById('reportIfPalindrome').innerHTML = result;
console.log(result);
}
Related
I have a laTeX string like this
let result = "\\frac{x}{2}+\\frac{3}{x}";
I want to find the index of "frac"s in the string and put them in a array then I want to find the first '}' char after "frac" and replace it with "}/" and finally remove "frac" from the string.
I used this block of code but it just work correctly when we have one "frac"
let result = "\\frac{x}{2}+\\frac{3}{x}";
if (result.indexOf("frac") != -1) {
for (let i = 0; i < result.split("frac").length; i++) {
let j = result.indexOf("frac");
let permission = true;
while (permission) {
if (result[j] == "}") {
result = result.replace(result[j], "}/")
permission = false;
}
j++;
}
result = result.replace('frac', '');
}
}
console.log(result)
OUTPUT: \\{x}//{2}+\\{3}{x}
Could anyone help me to improve my code?
Something like this?
frac(.+?)}
is the literal frac followed by a capture group that will capture one or more of anything .+ until a } and replace it with that anything plus a }/
Using the function replacement to grab index and replace
let result = "\\frac{x}{2}+\\frac{3}{x}";
let pos = [];
const newRes = result.replace(/frac(.+?)}/g,function(match, found, offset,string) {
console.log(match,found,offset,string)
pos.push(offset)
return `${found}/`; // return the found string with the added slash
})
console.log(pos)
console.log(newRes)
Older answer using two sets of code
let result = "\\frac{x}{2}+\\frac{3}{x}";
let re = /frac/gi, res, pos = [];
while ((res = re.exec(result))) {
pos.push(res.index);
}
const newRes = result.replace(/frac(.+?)}/g,"$1}/")
console.log(pos)
console.log(newRes)
Hi I'm working on a problem that requires me to 'returns the passed string convertedToCamelCase'
I tried doing it like this
let wordsArr = words.toLowerCase().split(" ")
for (let i = 1; i<wordsArr.length; i++){
wordsArr[i] = wordsArr[i].charAt(0).toUpperCase()
wordsArr.slice(1)
}
return wordsArr.join("")
but that doesnt seem to work and now im stuck
Something like this should work if it doesn't contain punctuation
let camelot = "I have to push the pram a lot";
const makeCamel = s => {
let camelArray = s.toLowerCase().split(' ')
let newArray = [camelArray[0]]
for (let i in camelArray) {
if (i >= 1) {
let capLetter = camelArray[i][0].toUpperCase()
let rest = camelArray[i].slice(1);
let newWord = capLetter + rest
newArray.push(newWord);
}
}
return newArray.join('');
}
makeCamel(camelot)
I'm working on freeCodeCamp's Palindrome Checker. My code is a bit messy but it pretty works on every test except the nineth one. palindrome("almostomla") should return false but in my code it returns trueinstead. I think my nineth code has a little problem but couldn't solve that. I wonder where am I missing something.
function palindrome(str) {
let str1 = str.replace(/[^a-zA-Z\d:]/gi, '');
let str2 = str1.replace(/,/gi, '');
let str3 = str2.replace(/\./gi, '');
let str4 = str3.replace(/_/, "-");
let myStr = str4.toLowerCase(); //My string is ready for play
for (let i = 0; i < myStr.length; i++) {
if (myStr[i] != myStr[myStr.length - (i+1)]) { //I think there is a little mistake on this line
return false;
} else {
return true;
}
}
The problem is that you're only checking the first and last characters of the string. You should return true only after all iterations have finished:
function palindrome(str) {
let str1 = str.replace(/[^a-zA-Z\d:]/gi, '');
let str2 = str1.replace(/,/gi, '');
let str3 = str2.replace(/\./gi, '');
let str4 = str3.replace(/_/, "-");
let myStr = str4.toLowerCase(); //My string is ready for play
for (let i = 0; i < myStr.length; i++) {
if (myStr[i] != myStr[myStr.length - (i + 1)]) {
return false;
}
}
return true;
}
console.log(palindrome("almostomla"));
console.log(palindrome("foof"));
console.log(palindrome("fobof"));
console.log(palindrome("fobbf"));
Note that your initial regular expression is sufficient - it removes all characters that aren't alphabetical, numeric, or :, so the other 3 regular expressions you run later are superfluous. Since you're using the i flag, you can also remove the A-Z from the regex:
const stringToTest = str.replace(/[^a-z\d:]/gi, '');
It would also probably be easier just to .reverse() the string:
function palindrome(str) {
const strToTest = str.replace(/[^a-z\d:]/gi, '');
return strToTest.split('').reverse().join('') === strToTest;
}
console.log(palindrome("almostomla"));
console.log(palindrome("foof"));
console.log(palindrome("fobof"));
console.log(palindrome("fobbf"));
I want to create a function that takes a string as its parameter and extracts the longest word. If there are multiple words of the same length (max), It extracts the first one. (By the way, the function ignores numbers and punctuation). Anyways, here's the code:
function extractLongest(testString){
var lenArr = [];
var finalResult = "";
window.onload = function(){
testString = testString.replace(/[^a-z " "]/gi, '');
testString = testString.split(" ");
for (var counter = 0; counter < testString.length; counter++){
lenArr[counter] = parseInt(testString[counter].length);
}
lenArr = lenArr.sort();
for (var counterTwo = 0; counterTwo < testString.length; counterTwo++){
if(parseInt(testString[counterTwo].length) == Math.max(...lenArr)){
finalResult = testString[counterTwo];
break;
}
}
}
return finalResult;
}
The problem is that it always returns "string" (the type of the variable, not its value.)
The problem is your use of window.onload inside a function. This is only setting the handler on the window, which will only run when an onload event fires. Your function does this and then immediately returns finalReuslts which will still be an empty string. Presumably, you want all this code to run when you call the function. It's not clear why you are doing that; removing it makes the function work:
function extractLongest(testString){
var lenArr = [];
var finalResult = "";
testString = testString.replace(/[^a-z " "]/gi, '');
testString = testString.split(" ");
for (var counter = 0; counter < testString.length; counter++){
lenArr[counter] = parseInt(testString[counter].length);
}
lenArr = lenArr.sort();
for (var counterTwo = 0; counterTwo < testString.length; counterTwo++){
if(parseInt(testString[counterTwo].length) == Math.max(...lenArr)){
finalResult = testString[counterTwo];
break;
}
}
return finalResult;
}
console.log(extractLongest("hello my name is stephen"))
In case it's useful, there is a simpler way to do this with reduce():
function extractLongest(testString){
testString = testString.replace(/[^a-z " "]/gi, '');
testString = testString.split(" ");
return testString.reduce(function(a, b) {
return a.length > b.length ? a : b
});
}
console.log(extractLongest("hello my designation is stephen"))
My code (below) searches a string for the 4 possible variations on a pattern that the string may contain dd[Q]dd[A], d[Q]d[A], dd[Z]dd[A], d[Z]d[A]. My goal is to always find the number between character Q and A (or Z and A) and return the number and index position.
I believe my code could be written in a much more efficient manner, but I'm not sure what it would be (I'm a beginner coder). Any thoughts?
{
var str = 'TY 111-222 4Q8A';
var result;
var index;
/*RegExp the 4 possible variations of the pattern*/
var srchAlpha = /\d\d\*?[Q]\d\d\*?[A]/i;
var srchBeta = /\d\*?[Q]\d\*?[A]/i;
var srchGamma = /\d\d\*?[Z]\d\d\*?[A]/i;
var srchDelta = /\d\*?[Z]\d\*?[A]/i;
/*Index the 4 possible variations of the pattern*/
var indexAlpha = str.search(srchAlpha);
var indexBeta = str.search(srchBeta);
var indexGamma = str.search(srchGamma);
var indexDelta = str.search(srchDelta);
/*Determine which variation of the pattern the string contains*/
if (indexAlpha != -1) {
result = str.slice(indexAlpha+3, indexAlpha+5);
index = indexAlpha+3;
} else if (indexBeta != -1) {
result = str.slice(indexBeta+2, indexBeta+3);
index = indexBeta+2;
} else if (indexGamma != -1) {
result = str.slice(indexGamma+3, indexGamma+5);
index = indexGamma+3;
} else if (indexDelta != -1) {
result = str.slice(indexDelta+2, indexDelta+3);
index = indexDelta+2;
} else {
result = "";
index = "";
}
document.getElementById("result").innerHTML = result;
document.getElementById("index").innerHTML = index;
}
<p>result: <span id="result"></span></p>
<p>index: <span id="index"></span></p>
If there might be no digits between the letters, then, I believe, [QZ](\d*)A will do.
Make it [QZ](\d+)A if at least one digit is expected.
If there will be one or two digits, use [QZ](\d{1,2})A.
Do the following to extract the digit(s) and index(es):
const regex = /[QZ](\d+)A/;
const input = "TY 111-222 4Q8A";
const match = input.match(regex);
if (!match)
// no match
const digits = match[1];
const digitsIndexes = input.indexOf(digits);
For two groups of digits (before and after the Q or Z character) use two capturing groups:
const regex = /(\d+)[QZ](\d+)A/;
// ...
const digitGroups = [ match[1], match[2] ];
const digitGroupsIndexes = digitGroups.map(group => input.indexOf(group));
For reference, based on Dmitry Parzhitsky's answer, I have the full answer here.
{
var regex = /(\d+)[QZ](\d+)A/;
var input = "TY 111-222 4Q8A";
var match = input.match(regex);
if (!match) {
digits = "";
digitsIndexes = "";
} else {
var digits = match[2];
var digitsIndexes = input.indexOf(digits);
}
document.getElementById("result").innerHTML = digits;
document.getElementById("index").innerHTML = digitsIndexes;
}
<p>result: <span id="result"></span></p>
<p>index: <span id="index"></span></p>