How do I remove the function in this code to reverse the order of the characters? All I would like this function to do is replace all vowels imputed with "er".
Here is the pastebin: http://pastebin.com/R9e0JRce
// JavaScript Document
function flip() {
var result = flipString(document.f.original.value);
document.f.flipped.value = result;
}
function flipString(aString) {
aString = aString.toLowerCase();
var last = aString.length - 1;
var result = "";
for (var i = last; i >= 0; --i) {
result += derpChar(aString.charAt(i))
}
return result;
}
function derpChar(c) {
if (c == 'a') {
return 'er'
}
else if (c == 'e') {
return 'er'
}
else if (c == 'i') {
return 'er'
}
else if (c == 'o') {
return 'er'
}
else if (c == 'u') {
return 'er'
}
return c;
}
If all you want to do is replace a set of characters, it could be done easily using a regular expression:
var str = 'abcdef';
var output = str.replace( /[aeiou]/g, 'er' );
result: erbcderf
more info here
Related
So I try build my own Javascript calculator as an exercise. Unfortunately when I try to use the eval() function with "=" button click to convert string into result, for example "2+2*2", nothing happens. Here's my code:
var draw = document.getElementById("result");
function calc(x) {
draw.innerHTML += x;
if (x === '=') {
draw.innerHTML = eval(draw.innerHTML);
} else if (x === 'c') {
draw.innerHTML = '0';
} else if (x === 'sqrt') {
draw.innerHTML = Math.sqrt(eval(draw.innerHTML));
} else if (x === 'pow') {
draw.innerHTML = Math.pow(eval(draw.innerHTML));
}
}
draw.innerHTML += x;
means if e.g. your string is 2*2 and you call
calc("sqrt")
the draws content will be
"2*2sqrt"
and thats not a valid expression, therefore the eval will fail. You may want to only concat if its not an operation:
function calc(x) {
if (x === '=') {
return draw.innerHTML = eval(draw.innerHTML);
} else if (x === 'c') {
return draw.innerHTML = '0';
} else if (x === 'sqrt') {
return draw.innerHTML = Math.sqrt(eval(draw.innerHTML));
} else if (x === 'pow') {
return draw.innerHTML = Math.pow(eval(draw.innerHTML),2);
}
draw.innerHTML += x;
}
That can be beautified with an object as a lookup table:
const result = n => eval(n),
sqrt = n => Math.sqrt(eval(n)),
pow = n => Math.pow(eval(n),2),
default = (n, add) => n + add;
function calc(in){
draw.innerHTML = ({"=":result, sqrt, pow}[in] || default)(draw.innerHTML, in);
}
Attempting to complete the algorithms on freeCodeCamp. I eventually found an approach that works, but i still don't understand why this method did not work for all cases.
function palindrome(str) {
var alphaNumericStr = str.replace(/\W/g,"");
var lowerCaseAlphaNumericString = alphaNumericStr.toLowerCase();
var arr = lowerCaseAlphaNumericString.split("");
arr.reverse();
var reversedString = arr.join("");
if(str === reversedString){
return true;
}
return false;
}
palindrome("race car");
You're comparing a string which has been stripped of spaces and converted to lowercase to the original string. Replace your conditional with:
if(lowerCaseAlphaNumericString == reversedString){
rethrn true;
}
return false;
Here's a little refactor if you're interested:
// ...
var reversedString = arr.join('');
return lowerCaseAlphaNumericString == reversedString;
demo
This is where you are going wrong if(str === reversedString)
Try this:
if(lowerCaseAlphaNumericString === reversedString) {
return true;
}
return false;
}
There could be another approach. In this approach, the corner cases are handled separately.
function check_Palindrome(input_str){
var astr = input_str.toLowerCase().replace(/\W/g,'');
var acount = 0;
if(astr==="") {
console.log("Not Palindrome.");
return false;
}
if ((astr.length) % 2 === 0) {
acount = (astr.length) / 2;
} else {
if (astr.length === 1) {
console.log("Palindrome.");
return true;
} else {
acount = (astr.length - 1) / 2;
}
}
for (var x = 0; x < acount; x++) {
if (astr[x] != astr.slice(-1-x)[0]) {
console.log("Not Palindrome.");
return false;
}
}
console.log("Palindrome.");
return true;
}
function ts_getInnerText(el) {
if (typeof el == "string") return el;
if (typeof el == "undefined") { return el };
if (el.innerText) return el.innerText; // Not needed but it is faster
var str = "";
var cs = el.childNodes;
var l = cs.length;
for (var i = 0; i < l; i++) {
switch (cs[i].nodeType) {
case 1: // ELEMENT_NODE
str += ts_getInnerText(cs[i]);
break;
case 3: // TEXT_NODE
str += cs[i].nodeValue;
break;
}
}
return str;
}
Now when i call this function in IE, it always gets undefined value which raise a error on consol so i added a check for undefined.
function ts_sort_caseinsensitive(a, b) {
if (a.cells.length == b.cells.length) {
if (!(typeof ts_getInnerText(a.cells[SORT_COLUMN_INDEX]) == 'undefined')) {
aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
if (aa == bb) {
return 0;
}
if (aa < bb) {
return -1;
}
return 1;
}
}
}
after that the columns are starts sorted on click but not properly.. such as i have to click twice to sort it for asc or desc order.
I am writing a function that will return an array with prime numbers.
The function should return an array with n elements. (n is a parameter) But it returns only one element. Why?
My codes:
function findPrimes(n)
{
var arr = [];
var currIndex = 0;
var sqrtNum;
var ceiledNum;
var ceiledIndex = 0;
var currCompose;
var res;
for (initNum = 2; arr.length < n; ++initNum)
{
sqrtNum = Math.sqrt(initNum);
ceiledNum = Math.ceil(sqrtNum);
for (currCompose = 2; currCompose <= ceiledNum; ++currCompose)
{
res = initNum % currCompose;
if (res == 0 && initNum != currCompose)
{
break;
}
else if (res == 0 && initNum == currCompose)
{
arr[currIndex] = initNum;
++currIndex;
break;
}
else if (res != 0 && initNum != currCompose)
{
continue;
}
else
{
console.log("Impossible result!");
}
}
}
return arr;
}
findPrimes(2); //return 2
findPrimes(10); //return 2 too
Jsbin
You should not be comparing initNum to currCompose. Keep in mind that initNum is the number you are checking (say, 71), and currCompose will be at most ceil(sqrt(initNum)) (say 9), so the two will never be equal.
Also note that it is best to append to the list and verify that no divisors where found only after the inner loop has finished.
This modified version works.
function findPrimes(n)
{
var arr = [];
var currIndex = 0;
var sqrtNum;
var ceiledNum;
var ceiledIndex = 0;
var currCompose;
var res;
var initNum;
for (initNum = 2; arr.length < n; ++initNum)
{
sqrtNum = Math.sqrt(initNum);
ceiledNum = Math.ceil(sqrtNum);
for (currCompose = 2; currCompose <= ceiledNum; ++currCompose)
{
res = initNum % currCompose;
if (res == 0 && initNum != currCompose)
{
break;
}
}
if (currCompose == ceiledNum+1)
{
arr[currIndex] = initNum;
++currIndex;
}
}
return arr;
}
var primes = findPrimes(6);
document.write(primes);
correct Line 14 of your code as follows and it works like charm.
for (currCompose = 2; currCompose <= initNum; ++currCompose)
function FindPrime(numbers){
if(numbers.constructor === Array){
output = [];
for (var i = numbers.length - 1; i >= 0; i--) {
if(isPrime(numbers[i]) == true){
output.push(numbers[i]);
};
};
return output;
}
}
function isPrime(numb){
if (numb % 2 == 0) return false;
for (var i=3; i<= Math.sqrt(numb); i = i + 2) {
if (numb % i == 0) {
return false;
}
}
return true;
}
numbers = [1,2,3,4,5];
test = FindPrime(numbers);
console.log('testing', test);
I'm trying to find the keycodes (if that's even what I need) and to change the character to the incremented keycode (this is just for a coding challenge) and it's not working
function LetterChanges(str) {
var newString = "";
var keyCode;
for(var i = 0; i < str.length; ++i)
{
keyCode = str.charCodeAt(i);
console.log(keyCode);
if( keyCode > 57 && keyCode < 122)
{
//add 1 to the keycode
newString += String.fromCharCode(i+1);
//console.log(String.fromCharCode(i+1));
}
else if(keyCode === 90)
{
//if it's a z being examined, add an a
newString += "a";
}
else
//it is a symbol, so just add it to the new string without change
newString += str[i];
}
return newString.toUpperCase();
}
console.log(LetterChanges("Charlie"));
change
newString += String.fromCharCode(i+1);
to
newString += String.fromCharCode(keyCode+1);
Jsfiddle: http://jsfiddle.net/techsin/pnbuae83/1/
function codeIncreaser(input) {
var str='', code=null;
Array.prototype.forEach.call(input, function (e) {
code = e.charCodeAt();
if ((code>64 && code<90) || (code>96 && code<122)) {
code++;
} else if (code == 90) {
code = 65;
} else if (code == 122) {
code = 97;
}
str += String.fromCharCode(code);
});
return str;
}
var text = codeIncreaser('abczABC');
console.log(text);
This accommodates lowercase letters as well.
and if you wanna make code somewhat compact you could do something like this...
function $(i) {
var s='', c;
Array.prototype.forEach.call(i, function (e) {
c = e.charCodeAt();
((c>64&&c<90)||(c>96&&c<122))?c++:((c == 90)?c=65:(c==122&&(c=97)));
s += String.fromCharCode(c);
});
return s;
}
console.log($('abczABC #-#'));