I am trying to call startsWith() string function on a JSON property value:
{"message":"xyzabc"}
var jsonResponse = JSON.parse(httpResponse.text);
var stringMessage = jsonResponse.message.toString();
if(stringMessage.startsWith('xyz')) {
...
}
but I get the error:
Object xyzabc has no method 'startsWith'
How can I do that?
The code is running on server side, Express on Node.js
It may be happen that your browser does not support the startsWith() function so you can use use the RegExp to overcame this problem like this...
var jsonObject={message:"xyzHELLO"};
var regex=new RegExp("^xyz");
if(regex.test(jsonObject["message"])){
alert("hello");
}
Live Demo HERE
[EDIT]
If you want to add the function startsWith() in your each and every string than you can add like this
if (String.prototype.startsWith !== "function") {
String.prototype.startsWith = function (searching) {
var regex = new RegExp("^" + searching);
if (regex.test(this.toString())) {
return true;
}
else {
return false;
}
}
}
and after that you can use like this:
var jsonObject = { message: "xyzHELLO" };
if (jsonObject["message"].toString().startsWith("xyz")) {
alert("start with");
}
else {
alert("not start with");
}
[EDIT]
if (String.prototype.startsWith !== "function") {
String.prototype.startsWith = function (searching) {
if (this.toString().indexOf(searching) == 0) {
return true;
}
else {
return false;
}
}
}
As per the comment by #nnnnnn and I also think it is good practice if we use the native function of the JavaScript, Thanks #nnnnnn.
Please double check your input JSON. Your code works like a charm with a correct JSON input in httpResponse.text.
var json = '{"message": "xyztest"}';
var jsonResponse = JSON.parse(json);
var stringMessage = jsonResponse.message.toString();
if(stringMessage.startsWith('xyz')) {
alert('It works!');
}
Also please make sure the browser you are working in supports startsWith method. Here you can find a list with all supported browsers.
If you need to work around the browser compatibility issues, you can use the widely supported indexOf method.
if(stringMessage.indexOf('xyz') === 0) {
alert('It works!');
}
HERE is a Fiddle for both cases.
Apparently, Js has startsWith function for the strings. However, using your own function to see if the string starts with the value should cause no error.
function StartsWith(s1, s2) {
return (s1.length >= s2.length && s1.substr(0, s2.length) == s2);
}
var jsonResponse = JSON.parse(httpResponse.text);
var stringMessage = jsonResponse.message.toString();
if(StartsWith(stringMessage,'xyz')) {
//Doing Stuff!
}
Related
I have JavaScript array contains links something like this:
var urls = ['url1','url2','url3'];
if (urls.indexOf(window.location.hostname) > -1)
{
// do something ...
}
else {
window.location.href = 'redirect url';
}
this code work well, but I tried to convert it to an array of objects like this:
var urls = [
{
'url':'url1'
},
{
'url':'url2'
},
{
'url':'url3'
},
];
if (urls.url.indexOf(window.location.hostname) > -1)
{
// do something ...
}
else {
window.location.href = 'redirect url';
}
But this code is not working!!
How I can convert the first code into array of objects, or how I can search in array?
Easiest solution is to use array.some
if(urls.some(function(item) { return item.url == window.location.hostname;})) {
// do something ...
} else {
window.location.href = 'redirect url';
}
more readably
var found = urls.some(function(item) {
return item.url == window.location.hostname;
});
if(found) {
// do something ...
} else {
window.location.href = 'redirect url';
}
First of all: Both definitions of your urls variable are JSON:
first definition is an array of Strings in JSON notation
second definition is an array of objects, each consisting of one property url as a string.
In order to search through the second one, you need to iterate over the objects array explicitly and compare the property explicitly (as one approach):
var found = false;
for ( var n = 0; n < urls.length; n++ )
{
if ( urls[n].url == window.location.hostname )
{
/// do something
found = true;
break;
}
}
if ( !found )
{
// do something other
}
Or may be
if(urls.map(function(obj){ return obj.url}).indexOf(window.location.hostname)>0){
// do something ...
}
else {
window.location.href = 'redirect url';
}
Using lodash version 4 or later, you could do this:
if (_(urls).map('url').includes(window.location.hostname)) {
// do something...
} else {
window.location.href = 'redirect url';
}
When it comes to arrays of objects you cannot access elements like what you have done in your code. You have to use a loop to travers through the elements or an inbuilt functions like filter,map.Without using inbuilt functions you can do something like this to get your work done.
function to search for a particular url in the array
function findURL(array,url) {
for (var i = 0; i < array.length; i++) {
if (array[i].url == url) {
return i;
}
}
return -1;
}
Put below piece of code where you want to check the condition
var urls = [
{
'url':'url1'
},
{
'url':'url2'
},
];
if(findURL(urls,window.location.hostname) > -1){
//do something ..
}else{
window.location.href = 'redirect url';
}
There are some answers which describe how to apply filter and map methods in your scenario.Therefore I thing i don't want to put those in my answer.
If you use jquery there is a function called grep which returns an array of items found.
var urls = [
{
'url':'url1'
},
{
'url':'url2'
},
];
var result = $.grep(urls, function(e){ return e.url == window.location.hostname; });
if (result.length == 0) { // nothing found
window.location.href = 'redirect url';
} else if (result.length == 1) { // one item found
//do something ..
// you can access the found item by result[0].foo if you want
} else { // multiple items found
}
I'm running this code:
jQuery.get("http://email.hackmailer.com/checkuser.php?email=".concat(document.getElementById('name').value).concat(document.getElementById('domain').value), function(data) {
if(data == "true") {
document.getElementById('containerThree').style = "background-color:#20bb47;";
}else{
document.getElementById('containerThree').style = "background-color:#b33535;";
}
document.getElementById('avail').style = "color:#272727;";
document.getElementById('emt').style = "color:#272727;";
});
It works fine in FireFox, but in chrome not at all. I've tried using .style.background = "#mycolorcode" but it still doesn't work in chrome(and in that case, firefox too).
Try this:
if (data === 'true') {
document.getElementById('containerThree').style.backgroundColor = '#20bb47';
} else {
document.getElementById('containerThree').style.backgroundColor = '#b33535';
}
http://devdocs.io/html/element/style
http://youmightnotneedjquery.com/
NOTE: 'true' is a string. You would most likely would rather use the Boolean true.
Based on the latest edit to your question, does this cleanup of your surrounding code help?
jQuery.get('http://email.hackmailer.com/checkuser.php?email='
.concat(document.getElementById('name').value)
.concat(document.getElementById('domain').value),
function (data) {
if (data === true) {
document.getElementById('containerThree').style.backgroundColor = '#20bb47';
} else {
document.getElementById('containerThree').style.backgroundColor = '#b33535';
}
document.getElementById('avail').style.color = '#272727';
document.getElementById('emt').style.color = '#272727';
});
You don't need to send a string as 'true' to check a condition. Use it like:
var data = true; //use boolean but not 'true' as string.
Then you can simple use it as follows:
jQuery.get("http://email.hackmailer.com/checkuser.php?email=" + document.getElementById('name').value + document.getElementById('domain').value, function(data) {
var colorValue = "#272727";
document.getElementById('containerThree').style.backgroundColor = data == "true"?"#20bb47":"#b33535";
document.getElementById('avail').style.color = colorValue;
document.getElementById('emt').style.color = colorValue;
});
BTW, I am not sure how .style = "background-color:#20bb47;"; is working for you.
I have a problem with following code:
var status = null;
var action = 1;
function test() {
if(status != null || action == 3) {
alert('Why am i her?');
}else {
alert('I should be here');
}
}
test();
I get expected results in Firefox and IE alert('I should be here'). But in Chrome i get alert('Why am i here?').
I'm not able to reproduce this for you, but I might just have the answer:
if(status !== null || action === 3) {
Compare the variable not just by value but also by type, by using an extra =
status and action var names seem too good to not be system reserved. maybe your chrome has something running with a status var allocated. try changing them to something else and see if it makes a difference.
var myStatus = null;
var myAction = 1;
function test() {
if(myStatus != null || myAction == 3) {
alert('Why am i her?');
}else {
alert('I should be here');
}
}
test();
I was using this to test if server returned data is json.
try {
json = $.parseJSON(resp);
} catch (error) {
json = null;
}
if (json) {
//
} else {
//
}
But it returns true if resp is a number lik 2 or 3 or... It returns null if resp is 0.
Any ideas how to avoid this false situation?
I'm outputting data using php:
echo 0; //returns null
echo 2; //returns as valid json
It appears, 0 is read as string, and 2 is read as number.
If you're expecting an integer, use parseInt:
try {
val = parseInt(resp, 10);
if(val > 0) /* act accordingly ... */
} catch (error) {
val = null;
}
If you want to know if the "JSON is valid," you can use something akin to the following:
function isValidJSON(string){
try {
$.parseJSON(string);
return true;
}
catch(e){ return false; }
}
I suggest something like:
// source from Angular source
function isJson(data) {
return (/^\s*[\[\{]/.test(data) && /[\}\]]\s*$/.test(data));
};
So...
if (isJson(resp))
json = $.parseJSON(resp);
else
alert ('another response: ' + resp);
Numbers like 2 or 3 are technically valid JSON data. Do you expect an object? See e.g. this SO post for methods of checking if the returned variable is an object.
Basically your workflow would be to try to parse it as JSON, and if it succeeds, check if it's an object/list (depending on what you expect).
Example:
try {
json = $.parseJSON(resp);
return (typeof(json) === "object")
} catch (error) {
json = null;
}
This question already has answers here:
How to test if a string is JSON or not?
(22 answers)
Closed 3 years ago.
I have a json string that is converted from object by JSON.Stringify function.
I'd like to know if it's json string or just a regular string.
Is there any function like "isJson()" to check if it's json or not?
I'd like to use the function when I use local storage like the code below.
Thank you in advance!!
var Storage = function(){}
Storage.prototype = {
setStorage: function(key, data){
if(typeof data == 'object'){
data = JSON.stringify(data);
localStorage.setItem(key, data);
} else {
localStorage.setItem(key, data);
}
},
getStorage: function(key){
var data = localStorage.getItem(key);
if(isJson(data){ // is there any function to check if the argument is json or string?
data = JSON.parse(data);
return data;
} else {
return data;
}
}
}
var storage = new Storage();
storage.setStorage('test', {x:'x', y:'y'});
console.log(storage.getStorage('test'));
The "easy" way is to try parsing and return the unparsed string on failure:
var data = localStorage[key];
try {return JSON.parse(data);}
catch(e) {return data;}
you can easily make one using JSON.parse. When it receives a not valid JSON string it throws an exception.
function isJSON(data) {
var ret = true;
try {
JSON.parse(data);
}catch(e) {
ret = false;
}
return ret;
}
Found this in another post How do you know if an object is JSON in javascript?
function isJSON(data) {
var isJson = false
try {
// this works with JSON string and JSON object, not sure about others
var json = $.parseJSON(data);
isJson = typeof json === 'object' ;
} catch (ex) {
console.error('data is not JSON');
}
return isJson;
}
Since the question is "How to check if it's a string or json" maybe a simple way would be to check for string, so you would have done something like this somewhere:
if (typeof data === 'string') { // check for string!
//... do something
} else {///... do something else}
Maybe that could be enough depending on your overall solution, just in case someone else is looking around.
I think returning parsed JSON at the same time is a good idea, so I prefer following version:
function tryParse(str) {
try {
return { value: JSON.parse(str), isValid: true }
} catch (e) {
return { value: str, isValid: false }
}
}
As you probably know JSON.parse("1234"), JSON.parse("0"), JSON.parse("false") and JSON.parse("null") won't raise Exception and will return true. all this values are valid JSON but if you want to see isValid is true only for objects (e.g: { "key": "value" }) and arrays (e.g: [{ "key": "value" }]) you can use following version:
function tryParse(str) {
try {
var parsed = JSON.parse(str);
return { value: parsed , isValid: typeof parsed === 'object'}
} catch (e) {
return { value: str, isValid: false }
}
}