I would like to get specific fruits values from URL string in JavaScript. The fruits that I would like to get is apple, pear, white pear, banana and banana brazil.
The value from url's that I should get are:
www.ourfruit.net/fruit/apple_is_healthy.html (value: apple)
www.ourfruit.net/fruit/pear_is_healthy.html (value: pear)
www.ourfruit.net/fruit_offer/white_pear_discount.html (value: white-pear)
www.ourfruit.net/fruit_offer/banana_love.html (value: banana)
www.ourfruit.net/fruit_export/banana_brazil_export.html (value: banana-brazil)
The value from url's that I should not get are:
www.ourfruit.net/fruit/red_apple_is_healthy.html
www.ourfruit.net/fruit_offer/green_banana_love.html
www.ourfruit.net/fruit_export/banana_brazil_yellow_quality_export.html
My attempt based on this solution Regular expression to find two strings anywhere in input is
function findFruits() {
var url_path = window.location.pathname;
var url_path = url_path.replace(/\//g, "_");
var url_path = url_path.replace("_", "");
var url_path = url_path.replace("_index.html", "");
if (-1 !== url_path.match(/^.*apple.*$/)) theFruit = "fruit_apple";
if (-1 !== url_path.match(/^.*pear.*$/)) theFruit = "fruit_pear";
if (-1 !== url_path.match(/^.*white.*pear.*$/)) theFruit = "fruit_white_pear";
if (-1 !== url_path.match(/^.*banana.*$/)) theFruit = "fruit_banana";
if (-1 !== url_path.match(/^.*banana.*brazil.*$/)) theFruit = "fruit_banana_brazil";
tagData.tagValue.push({
"tags": [{ "tag": "FRUIT_POPULATE", "value": theFruit }],
"isEvent": true,
"isTargeting": true })
}
jQuery(document).ready(function() {
findFruits();
});
It does work. The problem is even in another page the console only show result the last if statement. So in this case the result FRUIT_POPULATE: fruit_banana_brazil. If I change the last if statement position to another fruits then console still show value from the last if statement.
Question: How to show proper theFruit value from matched url string above?
Thank you