Javascript & Split Arrays - javascript

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");
}

Related

Checking for exact URL

I am having an issue checking for the URL in the pages on my site.
This is what I have.
Checking for the exact string works well:
var url = location.pathname;
if ("url:contains('texas-ignition-interlock')") {
$("body").addClass("texas-ppc-page");
}
But when I have page url with similar words, both classes were added to both pages.
var url = location.pathname;
if ("url:contains('texas-ignition-interlock-device')") {
$("body").addClass("texas-ppc-device-page");
}
I also tried indexOf, and is didn't work do to the pages with similar names.
This is what I tried, and this works for the first example. Second example will have the first class added too.
if (window.location.href.indexOf("texas-ignition-interlock") > -1) {
$("body").addClass("texas-ppc-page");
}
if (window.location.href.indexOf("texas-ignition-interlock-devices") > -1) {
$("body").addClass("texas-ppc-device-page");
}
Now, I can still use the indexOf version. I would simply target the stuff on one page using the class .texas-ppc-page, and on the second page I would target using both classes of .texas-ppc-page.texas-ppc-device-page.
Is there a better way of doing this with JS or jQuery?
You can use split("/") to split location.pathname into string arrays.
location.pathname will be similar to /questions/41968769/checking-for-exact-url so by splitting this string with "/" will result into
["", "questions", "41968769", "checking-for-exact-url"]
now you can perform indexOf("") and it will return non -1 value if string matched exactly, like in this case if i do indexOf("url") function will return -1, and if i do indexOf("checking-for-exact-url") it will return 3.
If you prefer to examine the strings similarly to how you were, you can leverage a regex, via .test as seen below with the placeholders ^ and $, for start and end, respectively. Otherwise, indexOf will match even a portion of the string. Check out the following...
var url = 'texas-ignition-interlock-devices';
console.log(/^texas-ignition-interlock$/.test(url)); // false
console.log(/^texas-ignition-interlock-devices$/.test(url)); // true

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));

Updating a URL by adding a value of 1

So let's say the URL I have is
"mywebsite.com/file/100/"
What I want is for it to be updated to
"mywebsite.com/file/101/"
"mywebsite.com/file/102/"
(and so on...)
when the keyword cannot be found.
init();
function init()
{
searchWord("key word");
}
function searchWord(word)
{
var pageResults = document.body.innerHTML.match(word);
if(pageResults)
{
alert("word found");
} else {
}
}
Right now my script searches for a key term, and what I need is for the page to be updated by a value of 1 (100 to 101 to 102 etc) when the keyword cannot be found.
I am a noob a Javascript, none of this code is mine. I just need help developing it. I have searched around for a while, but I can't find much.
Thanks.
Not sure if this gets points for elegance.
Split the url into segments
Dispose of empty segment caused by trailing "/" if present.
If the last segment is numeric, replace it with its numeric value + 1.
Join the segments back into a string.
(If you want the trailing slash you can re-add it.)
Code
var url = "mywebsite.com/file/100/"
var segments = url.split("/");
while(segments[segments.length-1]==""){
segments.pop();
}
var lastSegment = segments[segments.length-1];
if(!isNaN(lastSegment)){
segments[segments.length-1] = (parseInt(lastSegment)+1).toString();
}
updatedUrl = segments.join("/");
One liner just for fun.
var url = window.location.hostname + window.location.pathname.split('/').map(function(sgmt){return (sgmt != '' && !isNaN(sgmt)) ? parseInt(sgmt)+1 : sgmt}).join('/');
You may want to omit the window.location.hostname to use relative url paths instead. The next piece first splits the url at the / and then uses the .map() method on the new array. The function that gets passed looks for non-blank and numerical sections of the url. If it finds it, it adds 1. When finished, it makes the array a string again (with the new number in the url) using the .join() method.

How to delete an item from a serialized list?

I make a serialized list (with JQuery) and then want to delete a Parameter/Value pair from the list. What's the best way to do this? My code seems kinda clunky to take care of edge conditions that the Parameter/Value pair might be first, last, or in the middle of the list.
function serializeDeleteItem(strSerialize, strParamName)
{
// Delete Parameter/Value pair from Serialized list
var strRegEx;
var rExp;
strRegEx = "((^[?&]?" + strParamName + "\=[^\&]*[&]?))|([&]" + strParamName + "\=[^\&]*)|(" + strParamName + "\=[^\&]*[&])";
rExp = new RegExp(strRegEx, "i");
strSerialize = strSerialize.replace(rExp, "");
return strSerialize;
}
Examples / Test rig at http://jsfiddle.net/7Awzw/
EDIT: Modified the test rig to preserve any leading "?" or "&" so that function could be used with URL Query String or fragment of serialized string
See: http://jsfiddle.net/7Awzw/5/
This version is longer than yours, but imho it's more maintainable. It will find and remove the serialized parameter regardless of where it is in the list.
Notes:
To avoid problems with removing items in the middle of an array, we iterate in reverse.
For exact matching of parameter names, we expect them to start at the beginning of the split string, and to terminate with =.
Assuming there is just one instance of the given param, we break once it's found. If there may be more, just remove that line.
Code
function serializeDeleteItem(strSerialize, strParamName)
{
var arrSerialize = strSerialize.split("&");
var i = arrSerialize.length;
while (i--) {
if (arrSerialize[i].indexOf(strParamName+"=") == 0) {
arrSerialize.splice(i,1);
break; // Found the one and only, we're outta here.
}
}
return arrSerialize.join("&");
}
This fails a few of your tests - the ones with serialized strings starting with '?' or '&'. If you feel those are valid, then you could do this at the start of the function, and all tests will pass:
if (strSerialize.length && (strSerialize[0] == '?' || strSerialize[0] == '&'))
strSerialize = strSerialize.slice(1);
Performance Comparison
I've put together a test in jsperf to compare the regex approach with this string method. It's reporting that the regex solution is 49% slower than strings, in IE10 on 32-bit Win7.

JS Regex match string with $

I am trying to write something that would look at tweets and pull up info about stocks being mentioned in the tweet. People use $ to reference stock symbols on twitter but I cant escape the $.
I also dont want to match any price mention or anything like that so basically match $AAPL and not $1500
I was thinking it would be something like this
\b\$[a-zA-Z].*\b
if there are multiple matches id like to loop through them somehow so something like
while ((tweet = reg.exec(sym_pat)) !== null) {
//replace text with stock data.
}
This expression gives me an unexpected illegal token error
var symbol_pat = new RegExp(\b\$[a-z]*);
Thanks for the help if you want to see the next issue I ran into
Javascript AJAX scope inside of $.each Scope
Okay, you've stated that you want to replace the matches with their actual stock values. So, you need to get all of the matching elements (stock ticker names) and then for each match you're going to replace the it with the stock value.
The answer will "read" very similarly to that sentence.
Assume there's a tweet variable that is the contents of a particular tweet you're going to work on:
tweet.match(/\b\$[A-Za-z]+\b/g).forEach(function(match) {
// match looks like '$AAPL'
var tickerValue = lookUpTickerValue(match);
tweet.replace(match, tickerValue);
});
This is assuming you have some logic somewhere that will grab the ticker value for the given stock name and then replace it (it should probably return the original value if it can't find a match, so you don't mangle lovely tweets like "Barbara Streisand is $ATAN").
var symbol_pat = new RegExp('\\b\\$[a-z]+\\b','gi');
// or
var symbol_pat = /\b\$[a-z]+\b/gi;
Also, for some reason JS can not calculate the beginning of a word by \b, it just catches the one at the end.
EDIT: If you're replacing the stock symbols you can use the basic replace method by a function and replace that data with predefined values:
var symbol_pat = /(^|\s)(\$[a-z]+\b)/gi;
var stocks = {AAPL:1,ETC:2}
var str = '$aapl ssd $a a$s$etc $etc';
console.log(str);
str = str.replace(symbol_pat, function() {
var stk = arguments[2].substr(1).toUpperCase();
// assuming you want to replace $etc as well as $ETC by using
// the .toUpperCase() method
if (!stocks[stk]) return arguments[0];
return arguments[0].replace(arguments[2],stocks[stk]);
});
console.log(str);

Categories