remove double quotes from string using javascript
This question already has an answer here:
I think you should consider why the value is "false" instead of false instead.
Where is that value assigned, and is there any reason why you can't assign it as a proper boolean?
Otherwise you can do something like this:
function isStrTrueOrFalse(string) { return !string.toLowerCase().match(/false/);}
that way any string that is "false" returns false. Any other string returns true. This is because that "str" is true. No matter what the contents is.
You could also use the i
flag in the regex, instead of .toLowerCase()
:
function isStrTrueOrFalse(string) { return !string.match(/false/i);}
As described in comments.
The reason you're being down-voted is that you've misunderstood the way types are used in JavaScript. The following code:
var x = "thing";
Creates a string, containing the characters thing
and binds the variable x
to it. There are no quotes in the string. The quotes are a message to the parser that want to store a string.
Notice that when you log this value to the console, it puts quotes round the value to show it's a string, so it appears surrounded by quotes. These quotes are not stored.
The reason your replacement code doesn't work is that there are no quotes in the string in the first place.
If you wrote the following:
var y = ""thing"";
or
var z = '"thing"';
then you would have a string with quotes in it.
What you should be doing is parsing the string containing true
. The quickest way is probably this:
function parseBool(input) {
if (input == "true") { return true; }
else if (input == "false") { return false; }
else return null; // or false, or throw exception, or whatever
}
链接地址: http://www.djcxy.com/p/75074.html
上一篇: 将字符串转换为布尔值