javascript indexOf with JSON stringified objects - javascript

I'm trying to find out if a string exists like so:
var test1 = '{"packageId":"1","machineId":"1","operationType":"Download"},{"packageId":"2","machineId":"2","operationType":"Download"}';
alert("found: " + test1.indexOf('{"packageId":"1","machineId":"1","operationType":"Download"}', 0));
However, the result is always 0.
what gives?

Just in case this isn't a joke...
String.prototype.indexOf returns the occurence of a matching string within a target string, since you just look for the very first occurence of that line, it correctly returns zero.
If you modify your search-string (for example with some random letters), you will get -1 as result since it will not get found.
There is a practice using the binary not operator, to pretty much bring the result from .indexOf() down to a boolean expression. This would look like
var res = test1.indexOf('{"packageId":"1","machineId":"1","operationType":"Download"}');
if( ~res ) {
// we have a match
} else {
// no match at all
}
Without going into great detail, the not-operator will negate each bit from a byte, also the extra bit which is used to determine if the value is positive or negative. So, since in ECMAscript only very few values are evaluated to falsy values, negative values will evaluate to true.
To really have a boolean result, it would look like
if( !!~res ) { }
which again is not really neccessary in this case.
The far more often used practice to get the "right" result using .indexOf() (same goes for Arrays), is to check if the result is greater than -1
if( res > -1 ) { }

ya its correct indexOf will return starting index of the string you mention, thats y its gives 0. If string is not exist it return -1
Some sample example
var sample= "welcome to javascript";
alert ( sample.indexOf("welcome",0)); // return 0
alert ( sample.indexOf("come",0)); // return 3
alert ( sample.indexOf("came",0)); // return -1
alert ( sample.indexOf("javascript",0)); // return 11
Match :
if(sample.indexOf("welcome",0)>-1)
alert("match");
else
alert("Not match")l

Related

identifying numbers using javascript

How can I make a function that takes a string and checks if it is a number string or if it includes letters/other characters? I have no idea what to do... RegExp takes too long so is there another way?
You have to use isNaN() function (is Not a Number). It will return you true if it's not a number (that mean that it contains letter) and false if it's one.
Source :
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
You can check for isNaN and see if value is number if you don't want to go with RegExp.
let inpArgs = Number.parseInt(input);
if(!Number.isNaN(inpArgs)){
// this check ensures that your input is number
// Do what you have to do
}
else{
// Handle the error
}
But I would prefer the one line check using RegExp any day like below.
if(/^\d+$/.test(Number(input))){
// this says your input is Number
}
You can use typeof oprator to check whether it is a number or string.
function(anything){
if(typeof(anything)==='number'){ //do something} }
if(typeof(anything)==='string'){ //do something} }
Hope I answer your question.
Thanks.
You can use typeof in JavaScript to identify input Like
alert(typeof <your input>); or var identity = typeof <your input>;
and whatever string alert that match in Condition Like
if (identity == <alert message>){do something}else{do something}

Empty <p> element not actually empty? Ascii Control characters?

Using JavaScript, I'm going through an array of objects. If the object has 1 or more values that are not null or empty, a <p> element is created and then appended to the container element.
var tempElem = document.createElement("P");
if( item.valueOne !== '' )
tempElem.innerHTML += item.valueOne;
if( item.valueTwo !== '' )
tempElem.innerHTML += item.valueTwo;
if( tempElem.innerHTML !== '' )
containerElem.appendChild(tempElem);
The above does filter out most empty entries, however a few are somehow making it through to the page.
On chrome, it shows exactly <p></p>
I've done some analyzing, and before the last if-statement...
typeof tempElem.innerHTML = string
tempElem.innerHTML.length = 4
tempElem.innerHTML.charCodeAt(0) = 1
tempElem.innerHTML.charCodeAt(1) = 1
tempElem.innerHTML.charCodeAt(2) = 1
tempElem.innerHTML.charCodeAt(3) = 1
tempElem.innerHTML.charCodeAt(4) = NaN
I'm quite lost on this one. The actual data is in json and for these particular values, I'm seeing key:"". Which is exactly the same as the ones that are being filtered just fine.
I know I can check the values in javascript before creating any kind of dom element, but I'd like to know what's causing this and how to fix it directly.
Turns out it was due to my usage of the .trim() method.
STRING.trim() does not remove characters such as x00 (Start of Header), x01 (Start of Text), etc.
If present in an otherwise empty string however, these characters will still pass a ==="" check.
For my specific purposes, this simple regex fixes the issue:
str.match(/[^\x00-\x20\x7F]/)
(will return true if at least 1 non space or 'empty' character exists)

Sort array for object key that holds unique value

I have an array that looks like this:
var coll = [
{
prop1:true,
prop2:false,
id:"888399"
},
{
prop1:true,
prop2:true,
id:"/XS-555224"
},
{
prop1:false,
prop2:false,
id:"/DL-555444"
}
]
I want to sort the array so that the element with the ID that begins with "/DL" (for which there will always only be one) always starts at the top. How do I do that?
I don't feel like a custom sort will be the best choice because I don't have to compare elements against one another, I only have to find the one with the "/DL", slice it out, and insert it at the beginning of the array.
However, to do that, I'll still need to iterate over each element of the array to find the element and then perform a couple operations. So then I start thinking that I might as well just do the sort. The problem is how to write the correct condition to compare 2 items and checking the beginning of the ID string. So I figure that I can just simply test for the beginning of the String and return the value myself without comparison.
So I try this:
coll.sort(function(a,b){
var itemA = a.id;
var itemB = b.id;
if(itemA.lastIndexOf("/DL") === 0){
return 1;
}
});
But this comparison isn't working. What is wrong with my custom compare function? Thanks for any helpful tips.
Even though you are just looking for one record to move to the front you still need to check both parameters in the sort, it could be either one.
coll.sort(function(a,b) {
return a.id.indexOf('/DL') === 0 ? -1 : b.id.indexOf('/DL') === 0 ? 1 : 0;
});
Basically we want the '/DL' record to be the 'lowest' value in the array so it will show up first (sort orders things low to high). If a is lower we return negative, if b is lower we return positive. So when sorting if a is the /DL we need to return a negative. If b is the /DL we return a positive. So this expression in english is basically "Is a is our record? -1. If not, is b our record? 1. If neither then 0."
you can try this:
var orderedArr = coll.sort(function(val){
return !val.id.toString().startsWith('/DL');
});
[EDIT]
Once that you have user with IE, you can add this to make your life easier in the future:
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
so you'll be able to use startsWith now and whenever you want.

Finding neighbors in a game of five-in-a-row

I can declare a winner if a player gets five of their tokens in a row, and now I am trying to implement the feature of capturing an opponent's pieces. For example, I am player X, I can trap O's pieces like this X00X in any direction on the board. In order to implement this, is the following logic correct:
Find all neighbors around O, check and see if the neighbor is an X or an O, if there are two 0's in a row surrounded by an X on each side, I can take those pieces. Is there a better way to approach this problem? I am thinking of something like this:
function isOCaptured(token, row, col){
if(gameBoard[row][col]==="O" && gameBoard[row][col+1] === "X"
&& gameBoard[row][col-1] === "X"){
return true;
}
return false;
}
But it does not seems to return true when I place one O in between two X's.
Here is what my server.js and app.js look like right now: https://jsfiddle.net/Amidi/s3gnx3rL/4/ The HTML is just a 13 x 13 grid of buttons with an event attached to each which sends the buttons coordinates to the add() function in my app.js
Now, the problem seems to be that the code only works if the "O" was placed last. This can be solved with a for-loop.
for(var i = -1; i <= 1; i++) {
if (gameBoard[row][col+i]==="O" && gameBoard[row][col+i+1] === "X"
&& gameBoard[row][col+i-1] === "X") {
return true;
}
}
return false;
You can also use a slice:
// The closest 5 cells to the left/right of the newly added piece, as a string
var str = gameBoard[row].slice(col-2,col+3).join("");
// Look for the pattern "XOX" in those 5 cells. Double negation to return bool.
return !!str.match("XOX");
Old answer
According to your comment, the code was called like this:
if(isOCaptured(x,y)===true){console.log("y is between 2 x\s");
This means that the function is called with two instead of three arguments. That will result in the following values of the arguments: token = x, row = y and col = undefined.
The expression being evaluated will thus be:
gameBoard[y][undefined]==="O" && gameBoard[y][undefined+1] === "X"
&& gameBoard[y][undefined-1] === "X"
Which would evaluate as follows:
Evaluating gameBoard[y] will succeed, resulting in a column (the wrong one though).
Then we try indexing the column with undefined, and since the array doesn't contain an element called undefined, it will fail, resulting in (again) undefined.
Then we compare this value undefined with "0", which is obviously false.
The expression false && ... will return false, as will the whole function.
If the second part would have been executed, it would calculate undefined+1, which is (quite accurately) evaluated to NaN (not a number). The array doesn't contain NaN either, so this calculation would evaluated to false as well.
Now, for some advice:
The statement if(expr){return true} else {return false} can be simplified to just return expr.
These kinds of bugs are pretty easy to find if you use the Chrome Debugger (or Firebug for firefox), where you can step through the code and see exactly what happens and where stuff goes wrong.

jquery check is string is inside a string

I got 2 variables;
value = 'com';
longString= "com-233-123-232-123";
I'd like to check if "value" is inside "longString". I tried using regex with test() but I fail, maybe you know better.
I think the indexOf(substr, [start]) is enough no need to regex.
indexOf(substr, [start])
Searches and (if found) returns the index number of the searched character or substring within the string. If not found, -1 is returned. "Start" is an optional argument specifying the position within string to begin the search. Default is 0.
http://www.javascriptkit.com/javatutors/string4.shtml
Two ways
1st indexOf
if (longString.indexOf(value) != -1)
// found
else
// not found
2nd split
var value = 'com'; var longString= "com-233-123-232-123";
var split1=longString.split("-");
var i=0;
var found=0;
while (i<split1.length)
{
if(split1[i]==value)
{
found=1;
break;
}
i++;
}
if(found==1)
//found
else
//not found
Don't use regular expressions for this - if the value you're looking for can be interpreted as a regular expression itself then you'll have trouble. Just check for longString.indexOf(value) != -1.
What does jQuery has to do with this? This is a simple Javascript problem
if (longString.indexOf(value) != -1)
// We found it
else
// We didn't find it

Categories