Find occurrences of string on array - JQuery - javascript

I need to find occurrences of a string on an array on the client side.
The examples on the JQuery Docs all use number comparisons, for some reason.
Basically I'm trying to do what in the Terminal is as easy as grep pattern < file.txt, but have the data come from an array instead of a file.
This is my code so far. Won't be much help but it'll give you an idea of how I try to accomplish this.
var array = [
'item 1 shalala',
'this is other item',
'more examples',
'dontknowwhatelsetosay',
'wildcard'
];
$( "#submit" ).keydown(function( event ) {
//console.log( "Handler for .keydown() called." );
var result = $.grep(array, function(value, i){
// No idea what to do.
// Will write the array elements that contain the pattern on a div using $('#divId').text(results);
});
});
I usually work on lower level languages, I hope the answer is not too obvious.
EDIT: #submit is on an input text field.

indexOf() will search for a substring in a string, it returns its position when found, or -1 when not found.
var result = $.grep(array, function(value) {
return value.indexOf(pattern) != -1;
}

Related

how to get the length of the given web element in protractor tests

I would like to find out the length of the variable which I get from the screen. If I use
var driverID = element(by.id('driverID')).getAttribute('value')
driverID.length
it is throwing and error as Property 'length' does not exist on type'Promise <string>. Can some one help me in finding the length of the string.
I would also like to know how to use string operations in protractor tests. In this case I want to know, if the string first index is 'character or a number' and the second index is 'character or a number'. I want to do this by using the length of the string.
use the count() method for the number of elements inside a Promise.
Now for your specific problem, you should do something like:
element(by.id('driverID')).getAttribute('value').then(function(attr) {
var length = attr.length; // I don't really need why you need this length
if (!isNaN(attr[0]) && !isNaN(attr[1])) {
// 1st and 2nd characters of the string are numbers.
}
})
try that:
var driverID = element(by.id('driverID')).getAttribute('value');
driverID.then((attribute) => {
console.log(attribute.length)
});
the second issue you can resolve using regex

jQuery Autocomplete Substring Matching

I'm attempting to do jQuery autocomplete such that I can search for multiple words.
For example, if I have smart, very smart, and super smart in a list I'd like to be able to start typing smar and have all three options show up.
This code will work in the sense that if I start typing from the very beginning like over it will suggest over smart which is correct. But it wouldn't suggest it if I type just smart which is the desired output.
Any idea how I can adjust the code so that I could search and suggest say a substring within the list?
http://jsfiddle.net/UKgD6/390/
var acList = ['smart',
'over smart',
'smart land',
'under smart',
'very smart'
];
$('#ac').autocomplete({
source: function( request, response ) {
var matches = $.map( acList, function(acItem) {
if ( acItem.toUpperCase().indexOf(request.term.toUpperCase()) === 0 ) {
return acItem;
}
});
response(matches);
}
});
Your issue can be fixed by changing the indexOf() check. Change === 0 to !== -1. This will return anything that matches, no matter what the index of the search string is within the actual string.
http://jsfiddle.net/UKgD6/391/

How to open a link using jQuery which has an exact pattern at the end of it?

How to get a link using jQuery which has an exact pattern at the end of it? E, g, I have the following code:
return $(document).find("a[href='https://my_site.com/XX-' + /\d(?=\d{4})/g, "*"]");
So, the links could be: https://my_site.com/XX-1635, https://my_site.com/XX-7432, https://my_site.com/XX-6426 and so on.
In other words, it could be any 4 digits after the "XX-".
You can use filter() for this.
reg = /https:\/\/my_site.com\/XX-\d{4}$/g;
elements = $(document)
.find("a")
.filter(function(){
return reg.test(this.href);
});
return elements;
You can use filter() with attribute starts with selector.
var regex = /XX-\d{4}$/; // Exact four digits after XX-
var anchors = $(document.body)
.find('a[href^="https://my_site.com/XX-"]')
.filter(() => regex.test(this.href));
Where is the source of your data?
I suspect the data you are trying to read is encoded for safe transport. This is where the space is converted to to %20 for example.
If true, you need convert your source data using encodeURIComponent(), then apply your find.
This might work (though my usage of search is weak). I have not tested this code but should give you an idea on direction...
// Collate all href from the document and store in array links
var links=[];
$(document).find("a").each(
function()
{
links.push( encodeURIComponent( $(this).prop("href") ) );
});
// Loop thru array links, perform your search on each element,
// store result in array results
var results=[];
results=links.filter(function(item){
return item.search('/\d(?=\d{4})/g');
});
console.log( results );
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
No need for jQuery at all. Simply can be accomplished by pure JS in a single line. It's probably multiple times faster too.
var as = document.getElementsByTagName("a"),
ael = Array.prototype.filter.call(as, e => /XX-\d{4}$/g.test(e.href));

Javascript jQuery: find array elements within a string

I think my question is fairly straightforward but I'm not very experienced with Javascript. What I am trying to do is pull the source code of a page and stick it all into a variable:
var sourcecode = document.documentElement.innerHTML;
Then I have an array of terms that I want to search that variable for:
var array = ['Huskers','Redskins','Texans','Rockets'];
I would like to assign a 0 to any of the array elements that aren't found in the sourcecode variable and a 1 to any that are. So, when the search is complete each array element will be represented by a variable that will either equal 1 or 0. Can anyone please give me a hint as to how I should go about this?
Thanks!
A bit cryptic but does what you need:
var source = 'lorem hello foo bar world';
var words = ['hello','red','world','green'];
words = words.map(function(w){ return +!!~source.indexOf(w) });
console.log(words); //=> [1, 0, 1, 0]
+!!~ casts a number of the boolean representation of the value returned by indexOf, same as:
return source.indexOf(w) == -1 ? 0 : 1;
But a bit shorter.
Note that indexOf matches strings within strings as well, if you want to match whole words you can use regex with word boundaries \b:
words = words.map(function(w) {
return +new RegExp('\\b'+ w +'\\b','gi').test(source);
});
If you want to find element in array you can use jquery $.inArray()
http://jsfiddle.net/hgHy4/
$(document).ready(function() {
var array = ['Huskers','Redskins','Texans','Rockets'];
alert($.inArray('Redskins', array));
});
This will returns index number of element inside an array if it is found. If the element is not found it will return -1

Javascript & Split Arrays

What I want to accomplish is simple. I want a button's text to change depending on what page your on.
I start this by using the following:
var loc_array = document.location.href.split('/');
Now that I have the url and split it in an array I can grab certain directories depending on the position, like so:
if (loc_array[loc_array.length-1] == 'stations'){
var newT = document.createTextNode("Stations & Maps");
}
Now this works if the directory is /test/stations/, however if someone types /test/stations/index.html then it doesn't work. How can you test against this without throwing in another if statement or using a similar conditional.
Actually both your examples work the same. /stations/ and /stations/index.html both get split into two strings; /stations/ has an empty string at the end. So length-2 would have worked. Where it wouldn't work would be /stations, which is up a level. But that wouldn't normally be an issue because if stations is a static directory, the web server will redirect the browser to /stations/ with the slash.
That won't happen if you're doing the routing yourself. If you're doing routing, it's not a good idea to index from the end of the list of path parts, are there might be any old rubbish there being passed as path-parameters, eg. /stations/region1/stationname2. In this case you should be indexing from the start instead.
If the application can be mounted on a path other than a root you will need to tell JavaScript the path of that root, so it can work out how many slashes to skip. You'll probably also need to tell it for other purposes, for example if it creates any images on the fly it'll need to know the root to work out the directory to get images from.
var BASE= '/path-to/mysite';
var BASELEVEL= BASE.split('/').length;
...
var pagename= location.pathname.split('/')[BASELEVEL];
// '/path-to/mysite/stations/something' -> 'stations'
I'm using location.pathname to extract only the path part of the URL, rather than trying to pick apart href with string or regex methods, which would fail for query strings and fragment identifiers with / in them.
(See also protocol, host, port, search, hash for the other parts of the URL.)
I don't think string splitting is the best approach here. I would do it using RegEx.
var reStations = /\/stations(\/)?/i;
if (reStations.test(document.location.href))
//Do whatever
Not sure exactly what you're looking for, see if this fits:
var loc_array = document.location.href.split('/');
// this will loop through all parts
foreach (var i in loc_array) {
switch (loc_array[i]) {
case "stations":
// do something
break;
// other cases
}
}
// or if you want to check each specific element
switch (loc_array[0]) {
case "stations": // assuming /stations/[something/]
if (typeof loc_array[1] != 'undefined' && loc_array[1] == "something") {
// do things
}
break;
}
if( document.location.href.split( "station" ).length > 1 ){
//...
}
I think I see where you are going with this... As someone stated above using a RegExp (regular expression) could be helpful... but ONLY if you had more than a single type of page to filter out (html/js/php/...), but for what it looks like you want to do. Try something like this:
var loc_array = document.location.href.split('/');
var i = loc_array.length-1;
var button_label = "default";
while(i>1)
{
//checks to see if the current element at index [i] is html
if(loc_array[i].indexOf(".html")>-1)
{
if(i>0)
{
var button_label = loc_array[i-1];
break;
}
}
i--;
}
alert(button_label);
What it does is:
capture the current URL(URI)
split it into an array
starting from the END of the array and working BACKWARDS, look for the first element that contains the ".html" file identifier.
We now know that the element BEFORE our current element contains the label we want to add to our buttons...
You can then take the value and assign it wherever you need it.
If you run out of elements, it has a default value you can use.
Not sure if this helps.....
I have tested the above code and it worked.
if (loc_array[4]=='stations')
if the url was http://www.example.com/test/stations/index.html, the values in the array would be:
[0] = "http:"
[1] = ""
[2] = "www.example.com"
[3] = "test"
[4] = "stations"
[5] = "index.html"
For simplicity's sake, supposing that there is an array of keywords (such as "station") that identify the pages, use a map and try to match its keys with the href string using indexOf,
var href = document.location.href ;
var identifiers = {
"station": "Stations & Maps" , //!! map keys to result strings
/* ... */
} ;
identifier_loop: //!! label to identify the current loop
for(var n in identifiers) { //!! iterate map keys
if( href.indexOf(n) !== -1 ) { //!! true if the key n in identifiers is in the href string
var newT = document.createTextNode( identifiers[n] ) ; //!! create new text node with the mapped result string
break identifier_loop ; //!! end iteration to stop spending ressources on the loop
}
}
Your example will show an empty string, cause the last item is empty; so you can simply make:
if (loc_array[loc_array.length-2] == 'stations')
{
var newT = document.createTextNode("Stations & Maps");
}

Categories