I created a function to do this.
var text="adsf [name]Victor[/name] dummytext [name]Elliot[/name] asdf [name]Jake[/name] asdf [foo]bar[/foo]";
alert( readTags(text,'name') ); //Victor,Elliot,Jake
alert( readTags(text,'foo') ); //bar
but now I like to implement a function that receive a string like this
[person]
[name]jake[/name]
[age]12[/age]
[/person]
and return a object like this
var object={};
object['person']={};
object['name']='jake';
object['age']='12';
return(object);
but I don't know how to loop through the text. How to deal with starting and ending tags?
like
[tag] [tag]value[/tag] [/tag]
I thought to find starting tag from left and ending tag from the right using indexOf('[tag]') and lastindexOf('[/tag]')
but doesn't work in this situation
[tag]value[/tag] [tag]value[/tag]
this is the previous function
function readTags(str,property){
var beginTag='['+property+']';
var endTag='[/'+property+']';
var values=new Array(0);
while(str.indexOf(beginTag)!=-1){
values[values.length]=strBetween(str,beginTag,endTag);
str=str.substring(str.indexOf(endTag)+endTag.length);
}
return(values);
}
function strBetween(string,strBegin,strEnd){ //StrBetween("abcdef","b","e") //return "cd"
var posBegin, posEnd;
posBegin=string.indexOf(strBegin);
string=string.substring(posBegin + strBegin.length);
posEnd=string.indexOf(strEnd);
string=string.substring(0,posEnd);
if ((posBegin==-1)||(posEnd==-1)){
return(null);
}else{
return(string);
}
}
Unless you have a good reason not to use JSON, don't do this. JSON handles all of those problems very well and can be floated around from server to client and vice versa quite easily.
But since this seems fun, I'll try and see if I can whip up an answer.
Since your structure resembles XML, just replace the brackets with < and > and parse it like XML:
text = text.replace('[', '<').replace(']', '>');
if (typeof DOMParser != "undefined") {
var parser = new DOMParser();
var xml = parser.parseFromString(text, 'text/xml');
} else {
var xml = new ActiveXObject('Microsoft.XMLDOM');
xml.async = 'false';
xml.loadXML(text);
}
Now xml holds a DOMDocument that you can parse:
xml.getElementsByTagName('person').childnodes;
Try this possibly-working code (didn't test):
function createObject(element) {
var object = {};
if (element.childNodes.length > 0) {
for (child in element.childnodes) {
object[element.tagName] = createObject(child);
}
return object;
} else {
return element.nodeValue;
}
}
I thought this would be interesting to do without a third-party parser, so I built me a simple one:
function parse(code)
{
var obj = {},
cur = obj,
stack = [];
code.replace(/\[([^\]]+)\]|([^\[]*)/g, function (match, tagName, text) {
if (tagName)
{
if (tagName.charAt(0) == "/")
{
/* end tag */
cur = stack.pop();
}
else
{
/* start tag */
stack.push(cur);
cur = cur[tagName] = {};
}
}
else
{
cur["#text"] = text;
}
});
return obj;
}
var obj = parse(text);
JSON <=> XML http://code.google.com/p/x2js/
Related
I am looking for a JavaScript library that parses an XML string and converts it to a JavaScript object. What are some good ones?
The following function parses XML and returns a JavaScript object with a scheme that corresponds to the XML. XML siblings w/ the same name are collapsed into arrays. nodes with names that can be found in the arrayTags parameter (array of tag name strings) always yield arrays even in case of only one tag occurrence. arrayTags can be omitted. Text nodes with only spaces are discarded.
function parseXml(xml, arrayTags) {
let dom = null;
if (window.DOMParser) dom = (new DOMParser()).parseFromString(xml, "text/xml");
else if (window.ActiveXObject) {
dom = new ActiveXObject('Microsoft.XMLDOM');
dom.async = false;
if (!dom.loadXML(xml)) throw dom.parseError.reason + " " + dom.parseError.srcText;
}
else throw new Error("cannot parse xml string!");
function parseNode(xmlNode, result) {
if (xmlNode.nodeName == "#text") {
let v = xmlNode.nodeValue;
if (v.trim()) result['#text'] = v;
return;
}
let jsonNode = {},
existing = result[xmlNode.nodeName];
if (existing) {
if (!Array.isArray(existing)) result[xmlNode.nodeName] = [existing, jsonNode];
else result[xmlNode.nodeName].push(jsonNode);
}
else {
if (arrayTags && arrayTags.indexOf(xmlNode.nodeName) != -1) result[xmlNode.nodeName] = [jsonNode];
else result[xmlNode.nodeName] = jsonNode;
}
if (xmlNode.attributes) for (let attribute of xmlNode.attributes) jsonNode[attribute.nodeName] = attribute.nodeValue;
for (let node of xmlNode.childNodes) parseNode(node, jsonNode);
}
let result = {};
for (let node of dom.childNodes) parseNode(node, result);
return result;
}
Here's a nice xml2json and json2xml converter:
http://goessner.net/download/prj/jsonxml/
Related tutorial: http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html
Here's another one:
http://www.kawa.net/works/js/xml/objtree-e.html
Depending on your needs, you might be able to use a standard parser (see http://www.w3schools.com/XML/tryit.asp?filename=tryxml_parsertest2) and xpath (http://www.w3schools.com/xpath/default.asp) - here's an example:
http://snippets.dzone.com/posts/show/5272
and a few nice tutorials:
http://www.nczonline.net/blog/2009/03/17/xpath-in-javascript-part-1/
https://developer.mozilla.org/en/introduction_to_using_xpath_in_javascript
Going straight to the point (using node-xml2json):
npm install xml2json
Then, use it:
const parser = require('xml2json');
const obj = parser.toJson(xml, { object: true });
Example:
const parser = require('xml2json');
const xml = '<root><person><name>Bob Dylan</name></person></root>';
const obj = parser.toJson(xml, { object: true });
const { person } = obj.root;
person.name; // Bob Dylan
You can also convert from JSON to XML, and much more.
I wanted a simple Typescript version that didn't create additional #text objects and also disregarded attributes. If that's what you need, here's the code:
export class DomFuncs {
static parseNode = (node: Node) => {
const childNodes = node.childNodes;
if (childNodes.length === 0) {
return node.nodeValue;
} else if (childNodes.length === 1 && childNodes[0].nodeType === Node.TEXT_NODE) {
return childNodes[0].nodeValue;
} else {
const obj = {};
childNodes.forEach(childNode => {
const childName = childNode.nodeName;
const childValue = obj[childName];
if (childValue !== undefined) {
if (Array.isArray(childValue)) {
childValue.push(DomFuncs.parseNode(childNode));
} else {
obj[childName] = [childValue, DomFuncs.parseNode(childNode)];
}
} else {
obj[childName] = DomFuncs.parseNode(childNode);
}
});
return obj;
}
};
static xml2obj = (str: string) => {
const dom = (new DOMParser()).parseFromString(str, 'text/xml')
const result = {[dom.nodeName]: DomFuncs.parseNode(dom)};
return result;
}
}
To use it:
DomFuncs.xml2obj(xmlString);
This script currently disregards XML attributes since my converted object didn't require them. If you need that, let me know and I could update the code.
The xml2json javascript file from https://bitbucket.org/surenrao/xml2json is all you need to do this.
Here's the download link for quick download: https://bitbucket.org/surenrao/xml2json/get/0e0989dfe48e.zip
Once included in your project, here's some sample code to get you started:
var xmlStr = "<root><person><name>Bob Dylan</name></person></root>";
var jsObj = X2J.parseXml(xmlStr);
var result = jsObj[0].root[0].person[0].name[0].jValue; //Bob Dylan
I am looking for a JavaScript library that parses an XML string and converts it to a JavaScript object. What are some good ones?
The following function parses XML and returns a JavaScript object with a scheme that corresponds to the XML. XML siblings w/ the same name are collapsed into arrays. nodes with names that can be found in the arrayTags parameter (array of tag name strings) always yield arrays even in case of only one tag occurrence. arrayTags can be omitted. Text nodes with only spaces are discarded.
function parseXml(xml, arrayTags) {
let dom = null;
if (window.DOMParser) dom = (new DOMParser()).parseFromString(xml, "text/xml");
else if (window.ActiveXObject) {
dom = new ActiveXObject('Microsoft.XMLDOM');
dom.async = false;
if (!dom.loadXML(xml)) throw dom.parseError.reason + " " + dom.parseError.srcText;
}
else throw new Error("cannot parse xml string!");
function parseNode(xmlNode, result) {
if (xmlNode.nodeName == "#text") {
let v = xmlNode.nodeValue;
if (v.trim()) result['#text'] = v;
return;
}
let jsonNode = {},
existing = result[xmlNode.nodeName];
if (existing) {
if (!Array.isArray(existing)) result[xmlNode.nodeName] = [existing, jsonNode];
else result[xmlNode.nodeName].push(jsonNode);
}
else {
if (arrayTags && arrayTags.indexOf(xmlNode.nodeName) != -1) result[xmlNode.nodeName] = [jsonNode];
else result[xmlNode.nodeName] = jsonNode;
}
if (xmlNode.attributes) for (let attribute of xmlNode.attributes) jsonNode[attribute.nodeName] = attribute.nodeValue;
for (let node of xmlNode.childNodes) parseNode(node, jsonNode);
}
let result = {};
for (let node of dom.childNodes) parseNode(node, result);
return result;
}
Here's a nice xml2json and json2xml converter:
http://goessner.net/download/prj/jsonxml/
Related tutorial: http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html
Here's another one:
http://www.kawa.net/works/js/xml/objtree-e.html
Depending on your needs, you might be able to use a standard parser (see http://www.w3schools.com/XML/tryit.asp?filename=tryxml_parsertest2) and xpath (http://www.w3schools.com/xpath/default.asp) - here's an example:
http://snippets.dzone.com/posts/show/5272
and a few nice tutorials:
http://www.nczonline.net/blog/2009/03/17/xpath-in-javascript-part-1/
https://developer.mozilla.org/en/introduction_to_using_xpath_in_javascript
Going straight to the point (using node-xml2json):
npm install xml2json
Then, use it:
const parser = require('xml2json');
const obj = parser.toJson(xml, { object: true });
Example:
const parser = require('xml2json');
const xml = '<root><person><name>Bob Dylan</name></person></root>';
const obj = parser.toJson(xml, { object: true });
const { person } = obj.root;
person.name; // Bob Dylan
You can also convert from JSON to XML, and much more.
I wanted a simple Typescript version that didn't create additional #text objects and also disregarded attributes. If that's what you need, here's the code:
export class DomFuncs {
static parseNode = (node: Node) => {
const childNodes = node.childNodes;
if (childNodes.length === 0) {
return node.nodeValue;
} else if (childNodes.length === 1 && childNodes[0].nodeType === Node.TEXT_NODE) {
return childNodes[0].nodeValue;
} else {
const obj = {};
childNodes.forEach(childNode => {
const childName = childNode.nodeName;
const childValue = obj[childName];
if (childValue !== undefined) {
if (Array.isArray(childValue)) {
childValue.push(DomFuncs.parseNode(childNode));
} else {
obj[childName] = [childValue, DomFuncs.parseNode(childNode)];
}
} else {
obj[childName] = DomFuncs.parseNode(childNode);
}
});
return obj;
}
};
static xml2obj = (str: string) => {
const dom = (new DOMParser()).parseFromString(str, 'text/xml')
const result = {[dom.nodeName]: DomFuncs.parseNode(dom)};
return result;
}
}
To use it:
DomFuncs.xml2obj(xmlString);
This script currently disregards XML attributes since my converted object didn't require them. If you need that, let me know and I could update the code.
The xml2json javascript file from https://bitbucket.org/surenrao/xml2json is all you need to do this.
Here's the download link for quick download: https://bitbucket.org/surenrao/xml2json/get/0e0989dfe48e.zip
Once included in your project, here's some sample code to get you started:
var xmlStr = "<root><person><name>Bob Dylan</name></person></root>";
var jsObj = X2J.parseXml(xmlStr);
var result = jsObj[0].root[0].person[0].name[0].jValue; //Bob Dylan
I have a config.js file which I believe is JSON which is called when the application first starts:
var config={};
config.user = [
{id:'JSMITH', priceModify:'true'},
{id:'JBLOGGS', priceModify:'false'},
]
config.price = [
{id:"price01", name:"priceName01", primary:"57.25", secondary:"34.54"},
{id:"price02", name:"priceName02", primary:"98.26", secondary:"139.45"},
{id:"price03", name:"priceName03", primary:"13.87", secondary:"29.13"}
]
To pull / push data I just use the following:
// Read
var curPrice = config.price[0].primary;
// Write
config.price[0].primary = "98.24";
How do I go about exporting the config file with the new value so that it will load next time the application is opened? I can use the file system object to write the file, I just don't understand how I would export everything (and preferably keep the same format).
I originally thought about reading the whole config file into a variable, cycling through to find the required block, id, and key and replacing the value, then writing the whole thing back, but I can't seem to figure out how to replace that specific value only.
Any help would be greatly appreciated
Edit Apologies, I forgot to mention that this application is completely offline and uses local directories
Solution
I stumbled across a few solutions to different issues which, when combined, gave me the perfect solution. First we cycle the Javascript object, building an array of the detail and then converting the array to a string:
vMethod.convertToText = function(obj) {
var string = [];
var output = '';
var count= 0;
var countTotal = 0;
if (typeof(obj) == "object" && (obj.join == undefined)) {
count= 0;
countTotal = 0;
string.push("{");
for (prop in obj) {
countTotal++;
}
for (prop in obj) {
if(count==countTotal - 1) {
string.push(prop, ": ", vMethod.convertToText(obj[prop]),'}\r\n');
} else {
string.push(prop, ": ", vMethod.convertToText(obj[prop]), ",");
}
count++;
};
} else if (typeof(obj) == "object" && !(obj.join == undefined)) {
count= 0;
countTotal = 0;
string.push("[\r\n")
for (prop in obj) {
countTotal++;
}
for(prop in obj) {
if(count==countTotal - 1) {
string.push(vMethod.convertToText(obj[prop]),'];\r\n');
} else {
string.push(vMethod.convertToText(obj[prop]), ",");
}
count++;
}
} else if (typeof(obj) == "function") {
string.push(obj.toString())
} else {
string.push(JSON.stringify(obj))
}
output = string.join("").toString();
//output = output.slice(1, -1);
return output;
}
Then we clean the array (neccessary for me to remove excess characters)
vMethod.cleanConfigText = function() {
var outputText = vMethod.convertToText(config);
outputText = outputText.slice(1, -1);
outputText = 'var config = {};\r\n'+outputText;
outputText = outputText.replace('user:','config.user =');
outputText = outputText.replace(',price:','config.price =');
outputText = outputText.slice(0, -2);
outputText = outputText.replace(/"/g, "'")
return outputText;
}
Finally a function to export the object into my config.js file:
vMethod.writeToConfig = function() {
vObject.fileSystem = new ActiveXObject('Scripting.FileSystemObject');
vObject.fileSystemFile = vObject.fileSystem.CreateTextFile('source\\js\\config.js',true);
vObject.fileSystemFile.Write(vMethod.cleanConfigText());
vObject.fileSystemFile.Close();
delete vObject.fileSystemFile;
delete vObject.fileSystem;
}
So when I want to export a change in the config, I just call:
vMethod.writeToConfig();
The only difference in the file format is that the commas appear at the start of a trailing line rather than the end of a preceding line but I can live with that!
Edit Turns out I'm anally retentive and the commas were bugging me
Added these to the clean up function and now the config is identical to before but without the indent
outputText = outputText.replace(/[\n\r]/g, '_');
outputText = outputText.replace(/__,/g, ',\r\n');
outputText = outputText.replace(/__/g, '\r\n');
Thank you to those that looked at the question and tried to help, very much appreciated.
Edit
DO NOT READ THE SOLUTION ABOVE, IT IS IN THE WRONG PLACE AND THERFORE IS NOT A VALID ANSWER. YOU'VE BEEN WARNED.
You can use a very popular npm package: https://www.npmjs.com/package/jsonfile . There are many but I've choosen this one.
Usually config stuff should be in json or .env files.
Now, all you have to do is use jsonfile's API to read/write JSON and parse (the package does the serialization/deserialization) it at the beginning when the application starts.
Example:
var jsonfile = require('jsonfile');
var util = require('util');
var config = null;
var file = './config.json';
// Reading
jsonfile.readFile(file, function(err, obj) {
config = obj;
});
// Writing
// Edit your config blah blah
config.user = [
{id:'JSMITH', priceModify:'true'},
{id:'JBLOGGS', priceModify:'false'},
];
config.price = [
{id:"price01", name:"priceName01", primary:"57.25", secondary:"34.54"},
{id:"price02", name:"priceName02", primary:"98.26", secondary:"139.45"},
{id:"price03", name:"priceName03", primary:"13.87", secondary:"29.13"}
];
jsonfile.writeFile(file, config, function (err) {
if(err) return err;
console.log('Config saved to file!');
});
I am looking for a JavaScript library that parses an XML string and converts it to a JavaScript object. What are some good ones?
The following function parses XML and returns a JavaScript object with a scheme that corresponds to the XML. XML siblings w/ the same name are collapsed into arrays. nodes with names that can be found in the arrayTags parameter (array of tag name strings) always yield arrays even in case of only one tag occurrence. arrayTags can be omitted. Text nodes with only spaces are discarded.
function parseXml(xml, arrayTags) {
let dom = null;
if (window.DOMParser) dom = (new DOMParser()).parseFromString(xml, "text/xml");
else if (window.ActiveXObject) {
dom = new ActiveXObject('Microsoft.XMLDOM');
dom.async = false;
if (!dom.loadXML(xml)) throw dom.parseError.reason + " " + dom.parseError.srcText;
}
else throw new Error("cannot parse xml string!");
function parseNode(xmlNode, result) {
if (xmlNode.nodeName == "#text") {
let v = xmlNode.nodeValue;
if (v.trim()) result['#text'] = v;
return;
}
let jsonNode = {},
existing = result[xmlNode.nodeName];
if (existing) {
if (!Array.isArray(existing)) result[xmlNode.nodeName] = [existing, jsonNode];
else result[xmlNode.nodeName].push(jsonNode);
}
else {
if (arrayTags && arrayTags.indexOf(xmlNode.nodeName) != -1) result[xmlNode.nodeName] = [jsonNode];
else result[xmlNode.nodeName] = jsonNode;
}
if (xmlNode.attributes) for (let attribute of xmlNode.attributes) jsonNode[attribute.nodeName] = attribute.nodeValue;
for (let node of xmlNode.childNodes) parseNode(node, jsonNode);
}
let result = {};
for (let node of dom.childNodes) parseNode(node, result);
return result;
}
Here's a nice xml2json and json2xml converter:
http://goessner.net/download/prj/jsonxml/
Related tutorial: http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html
Here's another one:
http://www.kawa.net/works/js/xml/objtree-e.html
Depending on your needs, you might be able to use a standard parser (see http://www.w3schools.com/XML/tryit.asp?filename=tryxml_parsertest2) and xpath (http://www.w3schools.com/xpath/default.asp) - here's an example:
http://snippets.dzone.com/posts/show/5272
and a few nice tutorials:
http://www.nczonline.net/blog/2009/03/17/xpath-in-javascript-part-1/
https://developer.mozilla.org/en/introduction_to_using_xpath_in_javascript
Going straight to the point (using node-xml2json):
npm install xml2json
Then, use it:
const parser = require('xml2json');
const obj = parser.toJson(xml, { object: true });
Example:
const parser = require('xml2json');
const xml = '<root><person><name>Bob Dylan</name></person></root>';
const obj = parser.toJson(xml, { object: true });
const { person } = obj.root;
person.name; // Bob Dylan
You can also convert from JSON to XML, and much more.
I wanted a simple Typescript version that didn't create additional #text objects and also disregarded attributes. If that's what you need, here's the code:
export class DomFuncs {
static parseNode = (node: Node) => {
const childNodes = node.childNodes;
if (childNodes.length === 0) {
return node.nodeValue;
} else if (childNodes.length === 1 && childNodes[0].nodeType === Node.TEXT_NODE) {
return childNodes[0].nodeValue;
} else {
const obj = {};
childNodes.forEach(childNode => {
const childName = childNode.nodeName;
const childValue = obj[childName];
if (childValue !== undefined) {
if (Array.isArray(childValue)) {
childValue.push(DomFuncs.parseNode(childNode));
} else {
obj[childName] = [childValue, DomFuncs.parseNode(childNode)];
}
} else {
obj[childName] = DomFuncs.parseNode(childNode);
}
});
return obj;
}
};
static xml2obj = (str: string) => {
const dom = (new DOMParser()).parseFromString(str, 'text/xml')
const result = {[dom.nodeName]: DomFuncs.parseNode(dom)};
return result;
}
}
To use it:
DomFuncs.xml2obj(xmlString);
This script currently disregards XML attributes since my converted object didn't require them. If you need that, let me know and I could update the code.
The xml2json javascript file from https://bitbucket.org/surenrao/xml2json is all you need to do this.
Here's the download link for quick download: https://bitbucket.org/surenrao/xml2json/get/0e0989dfe48e.zip
Once included in your project, here's some sample code to get you started:
var xmlStr = "<root><person><name>Bob Dylan</name></person></root>";
var jsObj = X2J.parseXml(xmlStr);
var result = jsObj[0].root[0].person[0].name[0].jValue; //Bob Dylan
Alone, this code works:
CustomButton = {
1: function () {
alert("Just testing")
},
}
I add the code below and the code above stops working:
function getvisitingnow() {
return document.location;
}
function getcontents(uri) {
var req = new XMLHttpRequest();
req.open('GET', uri, true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200) {
return req.responseText;
}
}
};
req.send();
}
function regexforsitefound(uri, searchcontents) {
var re = new RegExp("\\<div class=g\\>.*?(?:\\<a href=\\\"?(.*?)\\\"?\\>.*?){2}\\</div\\>", "mi");
var sitefound = searchcontents.match(re);
if (sitefound[0]) return sitefound[0] else return null;
}
function regexforcategoryfound(uri, searchcontents) {
var re = new RegExp("\\<div class=g\\>.*?(?:\\<a href=\\\"?(.*?)\\\"?\\>.*?){2}\\</div\\>", "mi");
var categoryfound = searchcontents.match(re);
if (categoryfound[1]) return categoryfound[1] else return null;
}
function regexfordomainname(uri) {
var re = new RegExp("http://(?:[A-Za-z0-9-]+\\.)?[A-Za-z0-9-]+\\.[A-Za-z0-9-]+/?", "si");
var domainname = uri.match(re);
if (domainname) return domainname;
}
function regexforparentdir(uri) {
var re = new RegExp("http://(?:[A-Za-z0-9-]+\\.)?[A-Za-z0-9-]+\\.[A-Za-z0-9-]+/?", "si");
var parentdir = uri.match(re);
if (parentdir) return parentdir;
}
function getcomparisonlink(visitingnow) {
var searchuri = null;
var searchcontents = null;
var uri = visitingnow;
while(true) {
searchuri = 'http://www.google.com.br/search?';
searchuri += 'q='+ uri +'&btnG=Search+Directory&hl=en&cat=gwd%2FTop';
searchcontents = getcontents(searchuri);
var sitefound = regexforsitefound(searchcontents);
if (sitefound) {
var categoryfound = regexforcategoryfound(searchcontents);
if (categoryfound) {
return categoryfound;
}
} else {
var domainname = regexfordomainname(uri);
if (!domainname) {
var parentdir = regexforparentdir(uri);
uri = parentdir;
} else {
return null;
}
}
}
}
function clickedlink(event){
var visitingnow = getvisitingnow();
if (visitingnow) {
getcomparisonlink(visitingnow);
if (comparisonlink) {
tab.open(comparisonlink);
};
}
}
function createBookmarkItem() {
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
var item = document.createElementNS(XUL_NS, "toolbarbutton");
item.setAttribute("id", "Testing-Doit-Button2");
item.setAttribute("class", "bookmark-item pagerank");
item.setAttribute("tooltiptext", "Do it!");
item.setAttribute("oncommand", "testing_doit();");
return item;
}
function placeBookmarkItem() {
var toolbar = document.getElementById("PersonalToolbar");
var button = createBookmarkItem();
toolbar.appendChild(button);
}
Why?
try adding your functions one by one. see at which function your code stops working. then empty the function contents only to put it back with pieces at a time. check again where your code stops working. about there should be a syntax error.
But as Bobby suggests, the easier way is to try Firefox Errorlog, or maybe Firebug.
One little JavaScript-error can break a lot of things. You have forgotten to add semicolons in two places.
There needs to be a semicolon after sitefound[0] here:
function regexforsitefound(uri, searchcontents) {
var re = new RegExp("\\<div class=g\\>.*?(?:\\<a href=\\\"?(.*?)\\\"?\\>.*? ){2}\\</div\\>", "mi");
var sitefound = searchcontents.match(re);
if (sitefound[0]) return sitefound[0] else return null;
}
and one after categoryfound[1] here:
function regexforcategoryfound(uri, searchcontents) {
var re = new RegExp("\\<div class=g\\>.*?(?:\\<a href=\\\"?(.*?)\\\"?\\>.*?){2}\\</div\\>", "mi");
var categoryfound = searchcontents.match(re);
if (categoryfound[1]) return categoryfound[1] else return null;
}
if (sitefound[0]) return sitefound[0] else return null;
This syntax is invalid.
Try:
if (sitefound[0])
return sitefound[0];
else
return null;
If you are a Mac user, open (a recent version) of Safari and hit
⌥⌘ + i,
which opens up a great panel with lots of charts and data about the client-server interaction. You can also see and locate javascript errors, or debug javascript in a console directly. neat.
For Firefox, try the excellent firebug to see, what went wrong where .. in their own words: [with Firebug] .. you can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.
The comma after the function in CustomButton can break code the code in IE. Also, if you are using CustomButton the first time here, you should introduce it with var. I know these are not the issues you asked for, but otherwise, everything seems correct.