Cannot invoke function - javascript

See the bottom of this post;
function isVowel(aCharacter)
{
return ((aCharacter == 'a') || (aCharacter == 'A')||
(aCharacter == 'e') || (aCharacter == 'E')||
(aCharacter == 'i') || (aCharacter == 'I')||
(aCharacter == 'o') || (aCharacter == 'O')||
(aCharacter == 'u') || (aCharacter == 'U')||
(aCharacter == 'y') || (aCharacter == 'Y'));
}
function myF(aString)
{
// variable to hold resultString
var resultString = '';
// variable to hold the current and previous characters
var currentCharacter = '';
var precedingCharacter = '';
// in the case of the first character in the string there is no
// previous character, so we assign an empty string '' to the variable at first
//precedingCharacter = '';
// TODO part (ii)
// add code as directed in the question
var i = 0;
for( i; i < sString.length; ++i)
{
currentCharacter = sString.charAt(i);
if (isVowel(currentCharacter) && (!isVowel(precedingCharacter)))
{
resultString = resultString + 'ub';
}
resultString = resultString + currentCharacter;
precedingCharacter = currentCharacter;
}
return resultString;
}
var string1 = "the cat sat on the mat";
var result1 = myF(string1);
document.write(string1);//THIS ISN'T GOING TO BE DISPLAYED, BUT WHY?
document.write('<BR>');
document.write(result1);

You iterate on sString wich doesn't exist and not on your parameter aString.

Where is sString being declared in your function? Try with aString (or declare var sString = aString) and try again.

Please change function myF(aString) to function myF(sString)

There is a naming mistake. Here is a working copy of your code .
http://jsfiddle.net/hXarY/
You can try using "firebug" to catch such errors if you do not already do.
function isVowel(aCharacter)
{
return ((aCharacter == 'a') || (aCharacter == 'A')||
(aCharacter == 'e') || (aCharacter == 'E')||
(aCharacter == 'i') || (aCharacter == 'I')||
(aCharacter == 'o') || (aCharacter == 'O')||
(aCharacter == 'u') || (aCharacter == 'U')||
(aCharacter == 'y') || (aCharacter == 'Y'));
}
function myF(sString) // this should be sString , not aString
{
// variable to hold resultString
var resultString = '';
// variable to hold the current and previous characters
var currentCharacter = '';
var precedingCharacter = '';
// in the case of the first character in the string there is no
// previous character, so we assign an empty string '' to the variable at first
//precedingCharacter = '';
// TODO part (ii)
// add code as directed in the question
var i = 0;
for( i; i < sString.length; ++i)
{
currentCharacter = sString.charAt(i);
if (isVowel(currentCharacter) && (!isVowel(precedingCharacter)))
{
resultString = resultString + 'ub';
}
resultString = resultString + currentCharacter;
precedingCharacter = currentCharacter;
}
return resultString;
}
var string1 = "the cat sat on the mat";
var result1 = myF(string1);
document.write(string1);//THIS ISN'T GOING TO BE DISPLAYED, BUT WHY?
document.write('<BR>');
document.write(result1);

Related

Replace single quotes, but not if within double quotes to use JSON.parse()

I need a solution to only exchange pairs of single quotes, which are NOT within a pair of double quotes.
A simplified example (original is > 100 KB):
['Element1',"Element's2",{"Element3":"E3"},'Element4']
In this example Element's2 should not become Element"s2, but 'Element1' should become "Element1".
Background:
I need to extract some website data contained in big Javascript blocks. To get it i need JOSN.parse() which does not accept single quotes (') as quotes.
but i can not simply use replace(/'/g, '"'), because the single quote is also used as apostrophe in some texts like: "that's it".
BTW: As #hakre recommenced, a much more simple solution for my case was to use eval() instead of JOSN.parse(). With eval() there was no need to exchange the single quotes.
I made a second variant, which also cares about escaped quotes like:[\'Element1\',"Element's2",{"Elements3":"E3"},'Element\'s4']
but it is a bit slower and the code looks a bit more complicated (so i use the other variant):
function convert(input) {
var openQuote
var close = {symbol:null,level:0,firstPos:null}
openQuote = close;
const singleQuote = "'"
const doubleQuote = '"'
const replaceBy = '"'
var pairCount = 0
var data = Array.from(input)
function replacePair(data, newChar, firstPos, secondPos) {
data[firstPos] = newChar;
data[secondPos] = newChar;
pairCount++
}
function checkEscaped (data, pos, level = 0) {
if (pos <= 0) return level
if (data[pos-1] == "\\") { return checkEscaped(data,pos-1,level+1) }
return level
}
function checkQuotes(data,pos){
if (data[pos] == singleQuote) {
let level = checkEscaped(data, pos)
if (openQuote.symbol == null) {openQuote = {symbol: singleQuote, level: level, firstPos: pos}; return}
if (openQuote.symbol == singleQuote && openQuote.level == level) {replacePair(data,replaceBy,openQuote.firstPos,pos); openQuote = close; return;}
return
}
if (data[pos] == doubleQuote) {
let level = checkEscaped(data, pos)
if (openQuote.symbol == null) {openQuote = {symbol: doubleQuote, level: level, firstPos: pos}; return}
if (openQuote.symbol == doubleQuote && openQuote.level == level) {openQuote = close; return;}
}
}
for (let i=0; i < data.length; i++) {
checkQuotes(data,i)
}
var result = data.join("");
console.log(pairCount , "Pairs of Single Quotes exchanged")
return result
}
document.getElementById('start').addEventListener('click', () => {
var dataIn = document.getElementById('input').value;
var output = document.getElementById('output').value = convert(dataIn)
});
<html><body>
<button id="start">start</button><BR>
Input:<br><textarea id="input" name="w3review" rows="2" cols="100" spellcheck="false">
[\'Element1\',"Element's2",{"Elements3":"E3"},'Element\'s4']
</textarea><BR>
Output:<br><textarea id="output" name="w3review" rows="2" cols="100" spellcheck="false"></textarea>
</body></html>
I have build this script to solve my problem. Even if is downvoted, this one works for my case and is a bit more fast.
function convert(input) {
const singleQuote = "'"
const doubleQuote = '"'
const replaceBy = '"'
var firstSingleQuote = null
var firstDoubleQuote = null
var pairCount = 0
var data = Array.from(input)
function replacePair(data, newChar, firstPos, secondPos) {
data[firstPos] = newChar;
data[secondPos] = newChar;
pairCount++
}
function checkQuotes(data,pos){
if (data[pos] == singleQuote) {
if (firstSingleQuote == null && firstDoubleQuote == null) { firstSingleQuote = pos; return; }
if (firstSingleQuote != null && firstDoubleQuote == null) { replacePair(data,replaceBy,firstSingleQuote,pos); firstSingleQuote = null; return; }
if (firstSingleQuote == null && firstDoubleQuote != null) { return; }
if (firstSingleQuote != null && firstDoubleQuote != null) { return; }
}
if (data[pos] == doubleQuote) {
if (firstDoubleQuote == null && firstSingleQuote == null) { firstDoubleQuote = pos; return; }
if (firstDoubleQuote != null && firstSingleQuote == null) { firstDoubleQuote = null; return; } // todo: replace doubleQuote if wanted!!
if (firstDoubleQuote == null && firstSingleQuote != null) { return; }
if (firstDoubleQuote != null && firstSingleQuote != null) { return; }
}
}
for (let i=0; i < data.length; i++) {
checkQuotes(data,i)
}
var result = data.join("");
console.log(pairCount , "Pairs of Single Quotes exchanged")
return result
}
document.getElementById('start').addEventListener('click', () => {
var dataIn = document.getElementById('input').value;
var output = document.getElementById('output').value = convert(dataIn)
});
<html><body>
<button id="start">start</button><BR>
Input:<br><textarea id="input" name="w3review" rows="2" cols="100" spellcheck="false">
['Element1',"Element's2",{"Element3":"E3"},'Element4']
</textarea><BR>
Output:<br><textarea id="output" name="w3review" rows="2" cols="100" spellcheck="false"></textarea>
</body></html>

Replacing Values in a String

Forgive me if this question has already been asked; I've searched the site for this question and haven't stumbled upon it yet.
I'm creating a word-guessing game, and I'm having trouble with the last of my functions. The function arguments are a user-inputted character ("character"), a randomly generated word ("word"), and a scrambled version of that word ("scrmbldword"). As an example, the word could be "chilly", and the scrambled version would have a corresponding number of underscores "______". The role of this function is to take the user input, scan the "word" for that letter, and if it finds that letter in the word, to replace an underscore of the "scrmbldword" with the corresponding letter.
For instance, the word would be "chilly", and the user input would be the character "l"; I need the scrmbldword to become "___ll_".
function unscrambledWord(character, scrmbldword, word) {
for (k = 0; k < word.length; k++) {
if (character == word[k]) {
var tempLetter = word[k];
console.log(tempLetter)
tempWord = scrmbldword.replace(scrmbldword[k], character);
console.log(tempWord);
}
}
}
Thank you for all the answers, but when I copy and paste them into my code, they are not working. I'm trying to understand the code behind your various answers so I can edit them myself, but for the most part I don't get it. Perhaps it would help you all if I gave more context, so here's my file entirely...
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Word Guess Game</title>
</head>
<body>
<div>
<p id="directions-text">Type any letter to start playing</p>
<p id="userchoice-text"></p>
<p id="userguesslist-text"></p>
<p id="unscrambledword-text"></p>
</div>
<script type="text/javascript">
var userGuesses = [];
var unknownWord = "";
function wordGenerator() {
var computerChoices = ["lowly", "start", "chilly", "bun", "bead", "friend", "return", "view", "cloth", "frogs", "celery", "basin", "stand", "special", "broad", "abaft", "plead", "quartz", "mark", "tempt", "shop", "stone", "scorch", "taboo", "hoax", "spiffy", "insure"];
var cpuWord = computerChoices[Math.floor(Math.random() * computerChoices.length)];
console.log(cpuWord);
return cpuWord;
};
var computerWord = wordGenerator();
function scrambledWord(string) {
var knownWord = ""
if (string.length == 3) {
knownWord = "___"
} else if (string.length == 4) {
knownWord = "____"
} else if (string.length == 5) {
knownWord = "_____"
} else if (string.length == 6) {
knownWord = "______"
} else if (string.length == 7) {
knownWord = "_______"
}
return knownWord;
}
var unknownWord = scrambledWord(computerWord);
var directionsText = document.getElementById("directions-text");
var userChoiceText = document.getElementById("userchoice-text");
var userGuessList = document.getElementById("userguesslist-text");
var unscrambledWordText = document.getElementById("unscrambledword-text");
document.onkeyup = function (event) {
var userGuess = event.key;
if ((userGuess === "a") || (userGuess === "b") || (userGuess === "c") || (userGuess === "d") || (userGuess === "e") || (userGuess === "f") || (userGuess === "g") || (userGuess === "h") || (userGuess === "i") || (userGuess === "j") || (userGuess === "k") || (userGuess === "l") || (userGuess === "m") || (userGuess === "n") || (userGuess === "o") || (userGuess === "p") || (userGuess === "q") || (userGuess === "r") || (userGuess === "s") || (userGuess === "t") || (userGuess === "u") || (userGuess === "v") || (userGuess === "w") || (userGuess === "x") || (userGuess === "y") || (userGuess === "z")) {
userGuesses.push(userGuess);
directionsText.textContent = "";
userChoiceText.textContent = "You chose: " + userGuess;
userGuessList.textContent = "You have guessed: " + userGuesses;
unscrambledWordText.textContent = "The word is: " + unknownWord;
wordChecker(userGuess)
} else {
alert("You did not enter an alphabetical character.")
}
};
function wordChecker(input) {
if (computerWord.includes(input)) {
alert("You guessed a correct character")
unscrambledWord(input, unknownWord, computerWord)
} else {
alert("You guessed an incorrect character")
}
}
function unscrambledWord(character, scrmbldword, word) {
for (k = 0; k < word.length; k++) {
if (character == word[k]) {
var tempLetter = word[k];
console.log(tempLetter)
tempWord = scrmbldword.replace(scrmbldword[k], character);
console.log(tempWord);
}
}
}
As per my understanding, you can try this
function unscrambledWord(character, word, scrmbldword = "_".repeat(word.length)) {
return [...scrmbldword].map((d, i) => d == '_' && word[i] == character ? character : d).join('')
}
console.log(unscrambledWord('l', 'chilly'))
I think Nitish Narang is really a nice answer, but if you really want to use your existing function, you can try to define and use a replaceAt function, like this :
function unscrambledWord(character, scrmbldword, word) {
for (k = 0; k < word.length; k++) {
if (character == word[k]) {
var tempLetter = word[k];
console.log(tempLetter)
tempWord = scrmbldword.replaceAt(k, character);
console.log(tempWord);
}
}
}
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
unscrambledWord("l", "______", "chilly")
You can use the replace method with a RegExp that has the global flag, which tells us to replace all instances of that RegExp.
RegExp(`[^${character}]`, "g")
We're making a regex that matches any character except the provided character.
function unscrambledWord(character, word) {
const notCharacter = RegExp(`[^${character}]`, "g")
return word.replace(notCharacter, "_")
}

What is wrong with this code i have written? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to make all of the constants have next to them but nothing is working.
This is the javascript code here.
function opishConversion(text) {
var output = "";
for (var i = 0; i < text.length; i = i + 1) {
if ((text.charAt[i] !== "a") || (text.charAt[i] !== "A") || (text.charAt[i] !== "e") || (text.charAt[i] !== "E") || (text.charAt[i] !== "i") || (text.charAt[i] !== "I") || (text.charAt[i] !== "o") || (text.charAt[i] !== "O") || (text.charAt[i] !== "u") || (text.charAt[i] !== "U")) {
output += text.charAt[i] + "op";
} else {
output += text.charAt[i];
}
}
return output;
}
var text = prompt("Enter Text To Convert");
alert(opishConversion(text));
Any help would be appreciated.
charAt is a native method of the String primitive. It should be charAt(i) not charAt[i]
string.charAt is a function, not an indexed object. You need to use parantheses rather than square brackets.
so:
text.charAt(i);
rather than
text.charAt[i];
You also need to change your if statement to
&&
for AND instead of
||
corrected:
function opishConversion(text) {
var output = "";
for (var i = 0; i < text.length; i = i + 1) {
if ((text.charAt(i) !== "a") && (text.charAt(i) !== "A") && (text.charAt(i) !== "e") && (text.charAt(i) !== "E") && (text.charAt(i) !== "i") && (text.charAt(i) !== "I") && (text.charAt(i) !== "o") && (text.charAt(i) !== "O") && (text.charAt(i) !== "u") && (text.charAt(i) !== "U")) {
output += text.charAt(i) + "op";
} else {
output += text.charAt(i); //rather than text.charAt[i];
}
}
return output;
}
alert(opishConversion("aAbBcCdDeEfFgG"))
http://jsfiddle.net/8rrd9p9j/2/
chatAt() is a function so you should not be using square brackets
text.charAt(i);
All above answers will fix the issue that you have. However, I would also suggest you to simplify the logic by first changing the text to lowercase prior to the for loop.
http://jsfiddle.net/tr9qpqe8/
function opishConversion(text) {
var output = '';
var text = text.toLowerCase();
for (var i = 0; i < text.length; i++) {
if ((text.charAt(i) !== "a") || (text.charAt(i) !== "e") || (text.charAt(i) !== "i") || (text.charAt(i) !== "o") || (text.charAt(i) !== "u")) {
output += text.charAt(i) + "op";
} else {
output += text.charAt(i);
}
}
return output;
}
var text = prompt("Enter Text To Convert");
alert(opishConversion(text));

regex for inside javascript function

Here is the function
function getChecked(button, form)
{
var name;
for (i = 0; i < document.forms['CheckForm'].list.length; i++) {
name = "Check" + (i + 0);
if (document.forms['CheckForm'].list[i].checked == true) {
if (name == "Check0")
form.Check0.value = "2337667";
else if (name == "Check1")
form.Check1.value = "2335765";
else if (name == "Check2")
form.Check2.value = "2332651";
else if (name == "Check3")
form.Check3.value = "2328582";
}
How to write a regex to get the value for the values after form.check0.value by itself and if possible the values for form.check0.value and form.check1.value and etc.
You may be looking for something like this regex:
/\d{2,}/g
Example:
var s = 'function getChecked(button, form){\n var name;\n for (i = 0; i < document.forms["CheckForm"].list.length; i++) {\n name = "Check" + (i + 0);\n if (document.forms["CheckForm"].list[i].checked == true) {\n if (name == "Check0")\n form.Check0.value = "2337667";\n else if (name == "Check1")\n form.Check1.value = "2335765";\n else if (name == "Check2")\n form.Check2.value = "2332651";\n else if (name == "Check3")\n form.Check3.value = "2328582";\n }\n }\n}';
console.log(s.match(/\d{2,}/g));
Output:
["2337667", "2335765", "2332651", "2328582"];
As for that PHP sample provided by #Daverandom, that can be shortened significantly:
preg_match_all('/\d{2,}/', $str, $matches); // Get all numbers that are at least 2 characters long.
print_r($matches[0]);
As seen in this paste

JavaScript: Parsing a string Boolean value? [duplicate]

This question already has answers here:
How can I convert a string to boolean in JavaScript?
(102 answers)
Closed 4 years ago.
JavaScript has parseInt() and parseFloat(), but there's no parseBool or parseBoolean method in the global scope, as far as I'm aware.
I need a method that takes strings with values like "true" or "false" and returns a JavaScript Boolean.
Here's my implementation:
function parseBool(value) {
return (typeof value === "undefined") ?
false :
// trim using jQuery.trim()'s source
value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
Is this a good function? Please give me your feedback.
Thanks!
I would be inclined to do a one liner with a ternary if.
var bool_value = value == "true" ? true : false
Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:
var bool_value = value == 'true';
This works because value == 'true' is evaluated based on whether the value variable is a string of 'true'. If it is, that whole expression becomes true and if not, it becomes false, then that result gets assigned to bool_value after evaluation.
You can use JSON.parse for that:
JSON.parse("true"); //returns boolean true
It depends how you wish the function to work.
If all you wish to do is test for the word 'true' inside the string, and define any string (or nonstring) that doesn't have it as false, the easiest way is probably this:
function parseBoolean(str) {
return /true/i.test(str);
}
If you wish to assure that the entire string is the word true you could do this:
function parseBoolean(str) {
return /^true$/i.test(str);
}
You can try the following:
function parseBool(val)
{
if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1)
return true;
else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0)
return false;
return null;
}
If it's a valid value, it returns the equivalent bool value otherwise it returns null.
You can use JSON.parse or jQuery.parseJSON and see if it returns true using something like this:
function test (input) {
try {
return !!$.parseJSON(input.toLowerCase());
} catch (e) { }
}
last but not least, a simple and efficient way to do it with a default value :
ES5
function parseBool(value, defaultValue) {
return (value == 'true' || value == 'false' || value === true || value === false) && JSON.parse(value) || defaultValue;
}
ES6 , a shorter one liner
const parseBool = (value, defaultValue) => ['true', 'false', true, false].includes(value) && JSON.parse(value) || defaultValue
JSON.parse is efficient to parse booleans
Personally I think it's not good, that your function "hides" invalid values as false and - depending on your use cases - doesn't return true for "1".
Another problem could be that it barfs on anything that's not a string.
I would use something like this:
function parseBool(value) {
if (typeof value === "string") {
value = value.replace(/^\s+|\s+$/g, "").toLowerCase();
if (value === "true" || value === "false")
return value === "true";
}
return; // returns undefined
}
And depending on the use cases extend it to distinguish between "0" and "1".
(Maybe there is a way to compare only once against "true", but I couldn't think of something right now.)
Why not keep it simple?
var parseBool = function(str) {
if (typeof str === 'string' && str.toLowerCase() == 'true')
return true;
return (parseInt(str) > 0);
}
You can add this code:
function parseBool(str) {
if (str.length == null) {
return str == 1 ? true : false;
} else {
return str == "true" ? true : false;
}
}
Works like this:
parseBool(1) //true
parseBool(0) //false
parseBool("true") //true
parseBool("false") //false
Wood-eye be careful.
After looking at all this code, I feel obligated to post:
Let's start with the shortest, but very strict way:
var str = "true";
var mybool = JSON.parse(str);
And end with a proper, more tolerant way:
var parseBool = function(str)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if(str == null)
return false;
if (typeof str === 'boolean')
{
if(str === true)
return true;
return false;
}
if(typeof str === 'string')
{
if(str == "")
return false;
str = str.replace(/^\s+|\s+$/g, '');
if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
return true;
str = str.replace(/,/g, '.');
str = str.replace(/^\s*\-\s*/g, '-');
}
// var isNum = string.match(/^[0-9]+$/) != null;
// var isNum = /^\d+$/.test(str);
if(!isNaN(str))
return (parseFloat(str) != 0);
return false;
}
Testing:
var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", " true ", " TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");
var array_2 = new Array(null, "", false, "false", " false ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");
for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}
for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}
I like the solution provided by RoToRa (try to parse given value, if it has any boolean meaning, otherwise - don't). Nevertheless I'd like to provide small modification, to have it working more or less like Boolean.TryParse in C#, which supports out params. In JavaScript it can be implemented in the following manner:
var BoolHelpers = {
tryParse: function (value) {
if (typeof value == 'boolean' || value instanceof Boolean)
return value;
if (typeof value == 'string' || value instanceof String) {
value = value.trim().toLowerCase();
if (value === 'true' || value === 'false')
return value === 'true';
}
return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
}
}
The usage:
var result = BoolHelpers.tryParse("false");
if (result.error) alert(result.msg);
stringjs has a toBoolean() method:
http://stringjs.com/#methods/toboolean-tobool
S('true').toBoolean() //true
S('false').toBoolean() //false
S('hello').toBoolean() //false
S(true).toBoolean() //true
S('on').toBoolean() //true
S('yes').toBoolean() //true
S('TRUE').toBoolean() //true
S('TrUe').toBoolean() //true
S('YES').toBoolean() //true
S('ON').toBoolean() //true
S('').toBoolean() //false
S(undefined).toBoolean() //false
S('undefined').toBoolean() //false
S(null).toBoolean() //false
S(false).toBoolean() //false
S({}).toBoolean() //false
S(1).toBoolean() //true
S(-1).toBoolean() //false
S(0).toBoolean() //false
I shamelessly converted Apache Common's toBoolean to JavaScript:
JSFiddle: https://jsfiddle.net/m2efvxLm/1/
Code:
function toBoolean(str) {
if (str == "true") {
return true;
}
if (!str) {
return false;
}
switch (str.length) {
case 1: {
var ch0 = str.charAt(0);
if (ch0 == 'y' || ch0 == 'Y' ||
ch0 == 't' || ch0 == 'T' ||
ch0 == '1') {
return true;
}
if (ch0 == 'n' || ch0 == 'N' ||
ch0 == 'f' || ch0 == 'F' ||
ch0 == '0') {
return false;
}
break;
}
case 2: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
if ((ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'n' || ch1 == 'N') ) {
return true;
}
if ((ch0 == 'n' || ch0 == 'N') &&
(ch1 == 'o' || ch1 == 'O') ) {
return false;
}
break;
}
case 3: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
if ((ch0 == 'y' || ch0 == 'Y') &&
(ch1 == 'e' || ch1 == 'E') &&
(ch2 == 's' || ch2 == 'S') ) {
return true;
}
if ((ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'f' || ch1 == 'F') &&
(ch2 == 'f' || ch2 == 'F') ) {
return false;
}
break;
}
case 4: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
var ch3 = str.charAt(3);
if ((ch0 == 't' || ch0 == 'T') &&
(ch1 == 'r' || ch1 == 'R') &&
(ch2 == 'u' || ch2 == 'U') &&
(ch3 == 'e' || ch3 == 'E') ) {
return true;
}
break;
}
case 5: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
var ch3 = str.charAt(3);
var ch4 = str.charAt(4);
if ((ch0 == 'f' || ch0 == 'F') &&
(ch1 == 'a' || ch1 == 'A') &&
(ch2 == 'l' || ch2 == 'L') &&
(ch3 == 's' || ch3 == 'S') &&
(ch4 == 'e' || ch4 == 'E') ) {
return false;
}
break;
}
default:
break;
}
return false;
}
console.log(toBoolean("yEs")); // true
console.log(toBoolean("yES")); // true
console.log(toBoolean("no")); // false
console.log(toBoolean("NO")); // false
console.log(toBoolean("on")); // true
console.log(toBoolean("oFf")); // false
Inspect this element, and view the console output.
Enough to using eval javascript function to convert string to boolean
eval('true')
eval('false')

Categories