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.
Related
please help!
My goal is to filter the gmail inbox messages with Google App Script and find the specified Cyrillic word in it.
For example, I have a function that parse the messages:
var parseRawContent = function(rawContent)
{
var lines = rawContent.split("\n");
var result = {};
var headers = {};
var body = "";
var currentHeaderKey = null;
var headerParsed = false;
for (var i = 0; i < lines.length; i++) {
if (lines[i].trim() === "") {
if (headers.date === undefined) {
continue;
}
headerParsed = true;
continue;
}
if (!headerParsed) {
var headerParts = lines[i].match(/^([-a-z]+):(.*)/i);
if (headerParts) {
currentHeaderKey = headerParts[1].toLowerCase();
headers[currentHeaderKey] = headerParts[2].trim();
} else {
// Header continues on new line
headers[currentHeaderKey] += " " + lines[i].trim();
}
} else {
body += lines[i];
}
}
if (headers["content-transfer-encoding"] === "base64") {
try {
body = Utilities.newBlob(Utilities.base64Decode(body)).getDataAsString();
} catch (err) {
getLogger().log("Could not base64 decode body.")
}
}
result.headers = headers;
result.body = body;
return result;
};
Also, I have a function to spot the Russian text in the raw messages:
function(m, raw) {
"Has 'привет' in body"
return raw.body.match(/привет/i)
},
All the code above is taken from (https://github.com/spamzero/spamzero/blob/master/spam-zero.js)
Problem: the match does not happen.
What might be an issue?
Thank you
UPD: I found following issues with parsing the Gmail messages/threads
Russian text can be encoded with "Quoted Printable" encoding;
Russian text can be encoded with "Base64" encoding;
To manage all above the following changes were made for the original functions.
Parse function:
var parseRawContent = function(rawContent) {
var lines = rawContent.split("\n");
var result = {};
var headers = {};
var body = "";
var currentHeaderKey = null;
for (var i = 0; i < lines.length; i++) {
// Checking that the line is a header (starts with "<something>:")
var headerParts = lines[i].match(/^([-a-z]+):(.*)/i);
if (headerParts) {
currentHeaderKey = headerParts[1].toLowerCase();
headers[currentHeaderKey] = headerParts[2].trim();
} else {
// Decode Quoted-Printable to UTF-8 if applicable
if (headers["content-transfer-encoding"] === "quoted-printable") {
// check that the line is started with "=A0" or similar:
if (lines[i].match(/^=[0-9A-H]{2}=(.*)/)) {
try {
lines[i] = lines[i].replace(/=\s$/g, ''); // Replace the last "="
lines[i] = lines[i].replace(/={1}/g, '%'); // Replace all the "=" with "%" for decodeURI method
lines[i] = lines[i].split(" "); // Split the line into the words divided by space
var DecodedLine = ""
for (var j = 0; j < lines[i].length; j++) {
var SubLines = "";
SubLines = decodeURI(lines[i][j]);
DecodedLine += SubLines;
}
lines[i] = DecodedLine;
} catch (err) {
getLogger().log("Could not quoted-printable decode body.")
}
} else {
continue
}
}
// Decode base64 to UTF-8 if applicable
if (headers["content-transfer-encoding"] === "base64") {
try {
lines[i] = Utilities.newBlob(Utilities.base64Decode(lines[i])).getDataAsString();
} catch (err) {
getLogger().log("Could not base64 decode body.")
}
}
// Add everything that is not a header incl. decoded lines to BODY
body += lines[i];
}
}
result.headers = headers;
result.body = body;
return result;
};
Spot function:
function(m, raw) {
"Has Russian words 'тест' or 'привет' in body"
var matchers = [/тест/i, /привет/i
]
for (var i = 0; i < matchers.length; i++) {
if (raw.body.match(matchers[i])) {
return true;
}
}
},
An issue has been closed.
P.S.: I am a noob in coding. Please do not hesitate to comment/suggest more efficient solution.
The challenge is to "find Waldo." I'm trying to figure out how to find a word in a function/string." Return the index of where in the string 'Waldo' starts."
function findWaldo(str) {
var waldoPosition;
return waldoPosition
}
Simple task to do:
function findWaldo(str) {
return str.indexOf("waldo"); //the string you are looking for
}
It is explained quite well here.
There should be a library that does it easily, like string.indexOf, but you can do it manually with this algorithm:
int count = 0;
string yourText = "This is waldo?";
string toSearch = "waldo";
for (int x = 0; x < yourText.Lenght; x++)
{
if(yourText[x] == toSearch[0])
if((count + 1) == toSearch.Lenght)
return x;
else
count = 0;
//here we'd say ehh there's not Waldo on the string
}
To find a word or letter you can use x.indexOf method, hope to below code helps.
// Question
const findWord = (str, findWord) =>{
let total = ""
let error = false
let errorMessage = "";
if(str != null && str != ""){
error = false
if(!str.indexOf(findWord)){
total = `there is no ${findWord} in str peremeter.
`
}else{
total = `the position of ${findWord} is ${str.indexOf(findWord)}`
}
}else{
error = true;
errorMessage = "Please fill the str perimeter."
return errorMessage
}
return total
}
// Calling Function
console.log(findWord("Hello World", "World"))
I am trying to merger two json to one json. I don't want merge all keys, I added my code.
Code should be in javascript or node (underscore).
var json1 = [{user_id:1,friend_id:2,desc:'aaa'}, {user_id:3,friend_id:4,desc:'ccc'}, {user_id:1,friend_id:1,desc:'ccc'} , {user_id:1,friend_id:3,desc:'ccc'} ];
var json2 = [{reference_id:1,name:'A'},{reference_id:2,name:'B'},{reference_id:3,name:'C',age:30},{reference_id:4,name:'D'}];
Expecting Output:
output:
json1 = [{user_id:1,friend_id:2,desc:'aaa',user_name:'A',friend_name:'B'}, {user_id:3,friend_id:4,desc:'ccc',user_name:'C',friend_name:'D'}, {user_id:1,friend_id:1,desc:'ccc',user_name:'A',friend_name:'A'} , {user_id:1,friend_id:3,desc:'ccc',user_name:'A',friend_name:'C'} ];
Logic Js Code:
for (var i = 0; i < json1.length; i++) {
var user_id = json1[i].user_id;
var friend_id = json1[i].friend_id;
for (var j = 0; j < json2.length; j++) {
if (json2[j].reference_id == user_id) {
json1[i].user_name = json2[j].name;
}
if (json2[j].reference_id == friend_id) {
json1[i].friend_name = json2[j].name;
}
}
}
I attached my code in jsfiddle.Click Here
The same code should be convert into underscore.
You are repeating some effort here. Doesn't really matter if json2.length is small; but if it is large you will pay a penalty: you are looping over every element of json2 for every time you look at an element of json1. So instead, think of it this way:
var personMap = {};
json2.forEach(function(item) {
personMap[item.reference_id] = item.name;
});
json1.forEach(function(item) {
item.user_name = personMap[item.user_id];
item.friend_name = personMap[item.friend_id];
});
Your code in plain vanilla JS should work, except for "==" in the places where you've mistakenly put "=".
Replace these:
if (json2[j].reference_id = user_id) {
...
if (json2[j].reference_id = friend_id) {
...
with these:
if (json2[j].reference_id == user_id) {
...
if (json2[j].reference_id == friend_id) {
Try this is underscore:
_.map(json1, function(item){
var user_id = item.user_id;
var friend_id = item.friend_id;
_.map(json2, function(item2){
if (item2.reference_id == user_id) {
item.user_name = item2.name;
}
if (item2.reference_id == friend_id) {
item.friend_name = item2.name;
}
});
});
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>
alert(line) alerts 'ac'
typeof(line) is 'string'
When I run line.charAt(0), charAt is not a function.
When line is 'http://www.google.com/', it works,
I think it's the UTF-8 encoding of the file that I opened...
How to make charAt work with UTF-8?
UPDATED:
http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/src/effective_tld_names.dat?raw=1 is in my extension's chrome folder as effective_tld_names.dat
To run the code:
authority = 'orkut.com.br';
lines = sc_geteffectivetldnames();
lines = sc_preparetouse(lines);
domainname = sc_extractdomainname(authority, lines);
The code:
function sc_geteffectivetldnames () {
var MY_ID = "my#email.com";
var em = Components.classes["#mozilla.org/extensions/manager;1"].
getService(Components.interfaces.nsIExtensionManager);
var file = em.getInstallLocation(MY_ID).getItemFile(MY_ID, "chrome/effective_tld_names.dat");
var istream = Components.classes["#mozilla.org/network/file-input-stream;1"].
createInstance(Components.interfaces.nsIFileInputStream);
istream.init(file, 0x01, 0444, 0);
istream.QueryInterface(Components.interfaces.nsILineInputStream);
var line = {}, lines = [], hasmore;
do {
hasmore = istream.readLine(line);
lines.push(line.value);
} while(hasmore);
istream.close();
return lines;
}
function sc_preparetouse(lines) {
lines = sc_notcomment(lines);
lines = sc_notempty(lines);
return lines;
}
function sc_notcomment(lines) {
var line;
var commentre;
var matchedcomment;
var replacedlines;
replacedlines = new Array();
var i = 0;
while (i < lines.length) {
line = lines[i];
commentre = new RegExp("^//", 'i');
matchedcomment = line.match(commentre);
if(matchedcomment) {
lines.splice(i, 1);
} else {
i++;
}
}
return lines;
}
function sc_notempty(lines) {
var line;
var emptyre;
var matchedempty;
var replacedlines;
replacedlines = new Array();
var i = 0;
while (i < lines.length) {
line = lines[i];
emptyre = new RegExp("^$", 'i');
matchedempty = line.match(emptyre);
if(matchedempty) {
lines.splice(i, 1);
} else {
i++;
}
}
return lines;
}
function sc_extractdomainname(authority, lines) {
for (var i = 0; i < lines.length; i++) {
line = lines[i];
alert(line);
alert(typeof(line));
if (line.chatAt(0) == '*') {
alert('test1');
continue;
}
if (line.chatAt(0) == '!') {
alert('test2');
line.chatAt(0) = '';
}
alert('test3');
checkline = sc_checknotasteriskline(authority, line);
if (checkline) {
domainname = checkline;
}
}
if (!domainname) {
for (var i = 0; i < lines.length; i++) {
line = lines[i];
alert(line);
if (line.chatAt(0) != '*') {
alert('test4');
continue;
}
if (line.chatAt(0) == '!') {
alert('test5');
line.chatAt(0) = '';
}
alert('test6');
checkline = sc_checkasteriskline(authority, line);
if (checkline) {
domainname = checkline;
}
}
}
return domainname;
}
It alerts 'ac', then 'string', then nothing.
UPDATED:
I'm thinking there is a difference between files opened with nsIExtensionManager and NSIIOService, because that real code doesn't work, but this test code works:
function makeURI(aURL, aOriginCharset, aBaseURI) {
var ioService = Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
return ioService.newURI(aURL, aOriginCharset, aBaseURI);
}
URL = makeURI('file://C:/test/TLDs.dat');
// URL is a nsIURI; see nsIIOService::newURI for getting a string into a nsIURI.
var file = URL.QueryInterface(Components.interfaces.nsIFileURL).file;
// file is now a nsIFile
// open an input stream from file
var istream = Components.classes["#mozilla.org/network/file-input-stream;1"].
createInstance(Components.interfaces.nsIFileInputStream);
istream.init(file, 0x01, 0444, 0);
istream.QueryInterface(Components.interfaces.nsILineInputStream);
// read lines into array
var line = {}, lines = [], hasmore;
do {
hasmore = istream.readLine(line);
lines.push(line.value);
} while(hasmore);
istream.close();
// do something with read data
lines[0].charAt(0);
It's hard to tell what's going on without seeing any code, but remember that not all properties that evaluate as strings are really strings. A good example of this is the location object. Use of the object on its own will give you a string value, but you can't use any methods that are available to native strings on that string value.
// Although `window.location` returns a string, you cannot use String methods on it
alert(window.location.charAt(0)); // error
alert(window.location.href.charAt(0)); // no error
The same could be true of strings provided by external interfaces, such as plugins or ActiveX controls. The solution to this problem is to cast to a native string:
alert((""+window.location).charAt(0)); // auto casting with concatenation
alert(String(window.location).charAt(0)); // with the String() constructor
alert(window.location.toString().charAt(0)); // with toString()
At least the first two of those methods should solve your problem (replace window.location with your var). If not, try posting some code so we can get a better idea of what's happening.
Looking at your code, I can only assume that what I said above is correct. The readLine method returns a line object that contains the non-native string property value (which is rather odd, considering). I would suggest editing your code to look like this:
function sc_geteffectivetldnames () {
var MY_ID = "my#email.com";
var em = Components.classes["#mozilla.org/extensions/manager;1"].
getService(Components.interfaces.nsIExtensionManager);
var file = em.getInstallLocation(MY_ID).getItemFile(MY_ID, "chrome/effective_tld_names.dat");
var istream = Components.classes["#mozilla.org/network/file-input-stream;1"].
createInstance(Components.interfaces.nsIFileInputStream);
istream.init(file, 0x01, 0444, 0);
istream.QueryInterface(Components.interfaces.nsILineInputStream);
var line = {}, lines = [], hasmore;
do {
hasmore = istream.readLine(line);
lines.push(String(line.value)); // <--- or ""+line.value
} while(hasmore);
istream.close();
return lines;
}
I found URI Parsing for Firefox in MDC.
https://developer.mozilla.org/en/Code_snippets/URI_parsing
Somehow, it's not appearing on Google.