JavaScript look match substring in query with object - javascript

I would like to display a message on the page based on some value appearing in the URL. I have a known list of strings I'm looking for and the corresponding message. I cannot seem to get anywhere with the lookup / messaging. Could anyone pls kindly help? JavaScript only preferred, not jquery. Not that I the difference at this point ;)
Many thanks!
<div id="messagediv"></div>
Sample URLs to test:
<p>Campaign 1
<p>Campaign 2
<p>Campaign 3
<script>
(function () {
var params = window.location.search.substring(1).split('&'),
urlParams = {},
key, val;
for (var i = 01; i < params.length; i++) {
urlParams[params.split('=')[0]] = params.split('=')[1];
}
// querystring is ?utm_campaign=SpaCamp12458
// for instance, match URL query value SpaCamp12458 with the nums SpaComp key and show the corresponding text in the messagediv
var nums = {
defaultMessage: "Default Message",
"SpaComp": "Spas",
"PoolComp": "Recreation",
"BeachComp": "Outdoors"
}
for (var i in nums) {
if (nums.hasOwnProperty(i)) {
var found = false;
for (var j in urlParams) {
if (urlParams.hasOwnProperty(j)) {
if (urlParams[j].indexOf(nums[i]) === 0) {
document.getElementById("messagediv").innerHTML = nums[i];
found = true;
break;
}
}
}
if (!found) {
document.getElementById("messagediv").innerHTML = nums.defaultMessage;
}
}
}
})();
</script>

Related

Uncaught TypeError: Cannot read property 'dispatchEvent' of null

I am getting the above error when I run my function. The goal is when a user enters a number in a search box it should zoom to that number in the visualization. Below is my code -
function zoom1() {
var input1 = document.getElementById("myInput1").value; //value from searchbox
console.log("input from searchbox :"+input1);
d3.json("intervals.json", function(alldata) // entering json file to look for oid
{
// console.log("all data from json"+alldata);
var i=0;
for (i = 0; i < alldata.records.length; i++) //for loop for getting the "oid" alldata.records.length;
{
conceptid1 = alldata.records[i].eag; //saving all the oid in conceptid
console.log("conceptid1: "+conceptid1);
var conceptid2 = conceptid1.toString();
console.log("conceptid2: "+conceptid2);
if (conceptid2 === input1) //if the user input1 matches conceptid2
{
console.log("inside if conceptid2:"+conceptid2);
console.log(document.getElementById(conceptid2).dispatchEvent(new Event('click'))); // zoom
}
}
});
}
Can you share the console log for conceptid2?
By the way, use ES6 syntax. It's a newer and better way to write JS. Here is your code written in ES6:
const zoom = () => {
let value = document.querySelector("#myInput1").value;
console.log(`Input ${value}`);
d3.json("intervals.json", (alldata) => {
const { records } = alldata;
for (let i = 0; i < records.length; ++i) {
const conceptId = records[i].eag.toString();
console.log(`Concept ID: ${conceptId}`);
if (conceptId === value) {
// Your stuff
}
}
});
}
Anyways didn't want to come on too hard but I hope this helps :)

Problems with Arrays on Angular 5

I have this problem:
I have a search in the component "Table" (PrimeNg).
This search is to start when I post a character in the input. The search is correct, but when I clean the entry, the values do not return. This line at the beginning is just for this "this.groupExamples = this.Examples group;" but apparently when I change the elements of an array the other is affected.
public getGrupoExames(){
this.serviceExames.getGrupoExames()
.subscribe((response)=> {
this.grupoExames = response;
this.grupoExamesAux = response;
}, (erro)=> {
console.log("Erro");
});
}
private filtarGrupoExames(event){
let filtro: GrupoExame[] = [];
this.grupoExames = this.grupoExamesAux.slice();
for(let i = 0; i < this.grupoExames.length; i++) {
let grupo = this.grupoExames[i];
let listaExames = [];
for(let j = 0; j < grupo.exames.length; j++){
let exame = grupo.exames[j];
if(exame.nome.toLowerCase().indexOf(event.toLowerCase()) == 0) {
listaExames.push(exame);
}
}
grupo.exames = listaExames;
filtro.push(grupo);
}
this.grupoExames = filtro;
}
I suppose that you display whatever is inside your grupoExames, if that is correct you can try this structure
if(event.target.value.length > 1) {
do the filter
}
else {
this.getGrupoExames();
}
Maybe another more ambiguous solution is to create a button to delete the filter and access to all the content .
Hope it helps you!

Javascript, var contains

I currently use this script:
wHandle.setNick = function (arg) {
userNickName = arg;
var fnicks = ["porno","ibne","amcık","amcik","piç","salak","orospu","pkk","sik","kürdistan","kurdistan","kÜrdistan","kürt","sikeyim","sıkeyim","götoş","yönetici","YÖNETICI","YONETICI","yonetici","admın","admin","yarah","yarrah","agario","sike","s1ke","anan"];
var nctr = arg.toLowerCase();
if(fnicks.indexOf(nctr) > -1) {
alert("Unknown Nickname!");
} else {
hideOverlays();
sendNickName();
wjQuery("#mini-map-wrapper").show();
userScore = 0
wjQuery(".btn-needs-nick").prop("disabled", false);
}
};
I wanted to make some kind of filter, so that it blocks these nicknames BUT it isn't covering all of my cases. For example it blocks porno but not pornoo
I want it to use if(contains).
You've essentially done your logic backwards. Instead of checking if the nickname is in your block list, you'd be better served checking if an element of your blocklist is in your nickname like so:
var nick = args.toLowerCase();
for (var i; i < fnicks.length; i++) {
if (nick.indexOf(fnicks[i]) != -1) {
//bad name!
}
}
well I would just loop through the array, and search if the argument you pass (nctr in that case) contains the current entry (fnicks[i]).
you can replace the console.log() by your usual alert()
var arg = "pornoo";
var fnicks = ["porno","ibne","amcık","amcik","piç","salak","orospu","pkk","sik","kürdistan","kurdistan","kÜrdistan","kürt","sikeyim","sıkeyim","götoş","yönetici","YÖNETICI","YONETICI","yonetici","admın","admin","yarah","yarrah","agario","sike","s1ke","anan"];
var nctr = arg.toLowerCase();
for(var i=0,c=fnicks.length;i<c;i++) {
if(nctr.indexOf(fnicks[i]) > -1) {
console.log('boom');
}
}

Combining similar objects together in JavaScript

I have some javascript that is fetching some JSON and I'm trying to combine certain rows of information together to use in a table.
The JSON looks like below:
[{"Code":"12345","Name":"foo","Service":"Payments"},
{"Code":"12345","Name":"foo","Service":"Marketing"},
{"Code":"23456","Name":"bar","Service":"Payments"},
{"Code":"23456","Name":"bar","Service":"Development"},
{"Code":"34567","Name":"baz","Service":"Marketing"}]
Basically some rows share the exact same information with each other except for one field, Service.
My thought was to try to turn each row into an object that I can either update or merge with another object that shares the same Code.
That object and code looks something like this:
function CustObj(code,name,hasPay,hasMarket,hasDev) {
this.code = code;
this.name = name;
this.hasPay = hasPay;
this.hasMarket = hasMarket;
this.hasDev = hasDev;
}
function formatData(data) {
var formatedData = [];
for (var key in data) {
var customer = new CustObj(data[key].Code,data[key].Name);
switch (data[key].Service) {
case 'Payments':
customer.hasPay = true;
break;
case 'Marketing':
customer.hasMarket = true;
break;
case 'Development':
customer.hasDev = true;
break;
}
formatedData.push(school);
}
}
The problem is that I want to have one object for each unique Code but that has the correct amount of flags based on Service but I haven't figured out how to do that yet. I was looking at doing something like $.extend(formatedData,customer) to merge objects but I can't seem to get the right logic for locating the two objects that I'm trying to merge.
Any thoughts on how this can be accomplished?
You can process the array for duplicates and create a new array where the "Service" property is an array of services that share the same Code and Name:
var data = [
{"Code":"12345","Name":"foo","Service":"Payments"},
{"Code":"12345","Name":"foo","Service":"Marketing"},
{"Code":"23456","Name":"bar","Service":"Payments"},
{"Code":"23456","Name":"bar","Service":"Development"},
{"Code":"34567","Name":"baz","Service":"Marketing"}
];
function mergeServices(data) {
var result = [], item, match, found;
// for each array item
for (var i = 0; i < data.length; i++) {
item = data[i];
found = false;
for (var j = 0; j < result.length; j++) {
// see if we have a dup of a previously existing item
if (item.Code == result[j].Code && item.Name == result[j].Name) {
// just add the Service name to the array of the previous item
result[j].Service.push(item.Service);
found = true;
break;
}
}
if (!found) {
// copy the current row (so we can change it without changing original)
var newItem = {};
for (var prop in item) {
newItem[prop] = item[prop];
}
// convert service to an array
newItem.Service = [newItem.Service];
result.push(newItem);
}
}
return result;
}
var output = mergeServices(data);
That produces this output:
[
{"Code":"12345","Name":"foo","Service":["Payments","Marketing"]},
{"Code":"23456","Name":"bar","Service":["Payments","Development"]},
{"Code":"34567","Name":"baz","Service":["Marketing"]}
]
Working jsFiddle: http://jsfiddle.net/jfriend00/6rU2z/
As you create your customers you can add them to a map (an object) so that they can be referenced by code. You only create customers that are not already in the map. For each row you get or create the corresponding customer and set the corresponding flag.
function formatData(data) {
var customerMap = {};
$(data).each(function(index, elem){
// Get the customer if it is already in the map, else create it
var customer = customerMap[elem.Code];
if(!customer) {
customer = new CustObj(elem.Code, elem.Name);
customerMap[elem.Code] = customer;
}
// Add flags as appropiate
switch (elem.Service) {
case 'Payments':
customer.hasPay = true;
break;
case 'Marketing':
customer.hasMarket = true;
break;
case 'Development':
customer.hasDev = true;
break;
}
});
// Convert map to array
var formatedData = [];
for(var code in customerMap){
formatedData.push(customerMap[code]);
}
}
function CustObj(code,name) {
this.code = code;
this.name = name;
this.hasPay = false;
this.hasMarket = false;
this.hasDev = false;
}
EDIT I've created a fiddle to demonstrate this
JSFiddle

Using separators in JS

I'm currently writing a program that uses ";" as a seperator and extracts the url up until that point upon searching the content.
So it has the format:
name;surname
In searching the given arrays... I decided to go the extra mile and test for arrays without the ";" but this has confused the program - it has no idea of the ";" position anymore and this throws a spanner in the works!
Here is my code so far - many thanks in advance!
pages =
[
"The first", "An;alternative;page", "Yet another page"
]
u_c_pages =
[
"www.cam.ac.uk;"+pages[0]
,
"www.warwick.ac.uk"+pages[1]
,
"www.kcl.ac.uk;"+pages[1]
,
"www;"+pages[2]
]
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
var seperator = [];
var seperatorPos = [];
if(pattern)
{
for (var i = 0; i < u_c_pages.length; i++)
{
var found = true;
if((u_c_pages[i].indexOf(";"))<0)
{
found=false;
}
else
{
seperator[seperator.length] = i;
seperatorPos[seperatorPos.length] = (u_c_pages[i].indexOf("|"));
}
}
if(seperator.length==0)
{
return("Nothing found!");
}
else
var found2 = "";
{
for (var j = 0; j < seperator.length; j++)
{
if(u_c_pages[j].substring(seperatorPos[j],u_c_pages[j].length-1).toLowerCase().indexOf(pattern.toLowerCase()) >= 0)
{
found2 = (u_c_pages[j].substring(0,seperatorPos[j]));
break;
}
}
return(found2)
}
}
else
{
// only returned when the user decides to type in nothing
return("Nothing entered!");
}
}
alert(url1_m1(u_c_pages,pattern5));
enjoy the power of regex:
on JSFiddle
pages = ["The first", "An;alternative;page", "Yet another page"];
u_c_pages = [
"www.lboro.ac.uk;"+pages[0],
"www.xyz.ac.uk;"+pages[1],
"www.xyz.ac.uk;"+pages[1],
"www;"+pages[2]
];
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
// escape search pattern
pattern = pattern.toLowerCase().replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
pattern = new RegExp('^([^;]+);.*?' + pattern, 'i');
var result = null;
for(var i=0;i<u_c_pages.length;i++) {
if((result = u_c_pages[i].match(pattern))) {
return result[1];
}
}
return false;
}
alert(url1_m1(u_c_pages,pattern5));
You can use String.split(";") to split a string into segments. The parameter is the seperator.

Categories