i have a code like this and i get "Uncaught TypeError: Cannot call method 'replace' of undefined" in console, im not so good at javascript
<script>
parse_tag = function (str) {
var create_link = function (url, text) {
var link = $("<a>", {
text: text,
href: url,
target: "_blank"
});
return link.prop('outerHTML');
};
// parse username
str = str.replace(/[#]+[A-Za-z0-9_]+/g, function (s) {
return create_link("http://twitter.com/" + s.replace('#', ''), s);
});
// parse hashtags
str = str.replace(/[#]+[A-Za-z0-9_]+/g, function (s) {
return create_link("http://search.twitter.com/search?q=" + s.replace('#', ''), s);
});
return str;
};
$(document).ready(function() {
var text = $('.desc');
parse_tag(text);
});
</script>
You are calling the function like
var text = $('.desc');
parse_tag(text);
And the function is
parse_tag = function (str) { // <-- str suppose to be a string
var create_link = function(url, text){
// ...
return link.prop('outerHTML');
}
//...
str = str.replace(/[#]+[A-Za-z0-9_]+/g, function (s) {
return create_link("http://twitter.com/" + s.replace('#', ''), s);
});
}
In this case, str should be string but according to var text = $('.desc'); it's a jQuery object so you can change either var text = $('.desc'); to var text = $('.desc').text(); or make changes in your parse_tag function, otherwise, you'll get error something like object doesn't support this property or method.
Also, you are using two regex as /[#]+[A-Za-z0-9_]+/g, and /[#]+[A-Za-z0-9_]+/g but both are being used on a link, something like
#me`
Because you are returning an a tag using
return link.prop('outerHTML');
So, make changes in your regex too or maybe it's better to use the replace on link's text/href, so make sure you make the changes.
Related
I am making an ajax call in my javascript submit function. In this ajax call, I am passing an array(globalSelection) as data to the servlet. This array consists elements of function textSelection which is also pasted below.
globalSelection =[];
function submit() {
console.log("globalSelection start")
console.log(globalSelection)
console.log("globalSelection end")
$.ajax({
async : false,
type : "POST",
url : 'http://example.com:8080/myApp/DataServlet',
data: {globalSelection:globalSelection},
success : function(data) {
alert(data)
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
function textSelection(range, anchorNode, focusNode) {
this.range = range;
this.type = 3;
this.rCollection = [];
this.textContent = encodeURI(range.toString());
this.anchorNode = anchorNode;
this.focusNode = focusNode;
this.selectionId = getRandom();
this.yPOS = getYPOS();
this.getTagName = function(range) {
var el = range.startContainer.parentNode;
return el;
}
this.getTagIndex = function(el) {
var index = $(el.tagName).index(el);
return index;
}
this.simpleText = function(node, range) {
if (!node)
var entry = this.createEntry(this.anchorNode, this.range);
else
var entry = this.createEntry(node, range);
this.rCollection.push(entry);
this.highlight(this.rCollection[0].range);
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
this.compositeText = function() {
this.findSelectionDirection();
var flag = this.splitRanges(this.anchorNode, this.focusNode,
this.range.startOffset, this.range.endOffset);
if (flag == 0) {
for (j in this.rCollection) {
this.highlight(this.rCollection[j].range);
}
}
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
}
I am ading the screen of my browser console below, which prints the globalSelection(array).
In my servlet I am getting this array as follows
String[] arrays = request.getParameterValues("globalSelection[]");
System.out.println(arrays);
Here I am getting null value for arrays.
If I put globalSelection as follows in submit function for simple test to servlet, I am able to get the arrays.
var globalSelection = ["lynk_url", "jsonBody", "lynk_dummy1", "lynk_dummy2", "lynk_name", "lynk_desc", "lynk_flag"];
Why my actual globalSelection is shows null in servlet, what I am doing wrong here.
Try with :
String[] arrays = request.getParameterValues("globalSelection");
System.out.println(arrays);
Because the parameter submitted with name "globalSelection" only not "[]" symbol.
I see your problem and I have a simple solution.
I recommend in that case that you convert the array as a string in JS:
JSON.stringify(globalSelection)
and then reconstructing the object on the backend using some sort of library for JSON conversion like: https://code.google.com/archive/p/json-simple/
You could then do something like this:
JSONArray globalSelection = (JSONArray) new JSONParser().parse(request.getParameter("globalSelection"));
Iterator i = globalSelection.iterator();
while (i.hasNext()) {
JSONObject selection = (JSONObject) i.next();
String type = (String)selection.get("type");
System.out.println(type);
}
This will parse your array and print the selection type. Try it, hope it helps.
I'm trying to get my array of URL's to run through a JQuery .get function to get the site's source code into one string outside of the function. My code is below.
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var get = $.get(fetch, function(sourcecode) {
sourcecode = fetch;
}
I need the sourcecode variable to be the combination of source code on all of the URLs in the array.
You need to put a variable outside of the function, something like this data variable below and append to it with +=:
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var data = null;
var get = $.get(fetch, function(sourcecode) {
data += fetch;
}
}
Try this like,
var URL = ["http://website.org", "http://anothersite.com"];
var array = $(URL).map(function(fetch) {
var data='';
$.ajax({
url:fetch,
async:false,
success : function(d){
data=d;
}
});
return data;
}).get();
Since you're using jQuery, I suppose that jQuery.each() may be a better way to iterate over the array.
var URL = ["http://website.org", "http://anothersite.com"];
var str = [];
$.each(URL, function(index, fetch) {
$.get(fetch, function(sourcecode) {
str.push(sourcecode); // if you want an array
})
});
str.join(''); // if you want a string
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a javascript function for splitting the url for parameters and then setting the values of text fields with those parameters found. It works perfect... once I refresh the page. How can I get it to fill the text fields when the page loads?
$(function(){
var urlParams = {};
(window.onload = function () {
var match,
pl = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while((match = search.exec(query)) !== null)
urlParams[decode(match[1])] = decode(match[2]);
})();
window.onload=function(){
var nm= urlParams['name'];
var pn= urlParams['phone'];
var em= urlParams['email'];
document.getElementById('txtName').value=nm;
document.getElementById('txtPhone').value=pn;
document.getElementById('txtEmail').value=em;
}
})
Can anyone help me?
First of all, there is too much window.onload. jQuery's $(function(){}) will be fired when DOM will be ready, and this should be enough for your case. However I tried to reproduce your issue, but the function works for me. Try to remove window.onloads and tell me if it help. Maybe prepare some jsFiddle will be good too.
$(function(){
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while((match = search.exec(query)) !== null)
urlParams[decode(match[1])] = decode(match[2]);
})();
var nm= urlParams['name'];
var pn= urlParams['phone'];
var em= urlParams['email'];
document.getElementById('txtName').innerText=nm;
document.getElementById('txtPhone').innerText=pn;
document.getElementById('txtEmail').innerText=em;
})
Inside a web worker, I have an html string like:
"<div id='foo'> <img src='bar'></img> <ul id='baz'></ul> </div>"
Is there any library I can import to easily access id and src attributes of the different tags ? Is regex the only way inside a worker ?
There are two ways to solve this problem efficiently:
Regex
With the risk of getting false positives, you can use something like:
var pattern = /<img [^>]*?src=(["'])((?:[^"']+|(?!\1)["'])*)(\1)/i;
var match = string.match(pattern);
var src = match ? match[2] : '';
Built-in parser & messaging
If getting the HTML right is a critical requirement, just let the browser parse the HTML, by passing the string to the caller. Here's a full example:
Caller:
var worker = new Worker('worker.js');
worker.addEventListener('message', function(e) {
if (!e.data) return;
if (e.data.method === 'getsrc') {
// Unlike document.createElement, etc, the following method does not
// load the image when the HTML is parsed
var doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = e.data.data;
var images = doc.getElementsByTagName('img');
var result = [];
for (var i=0; i<images.length; i++) {
result.push(images[i].getAttribute('src'));
}
worker.postMessage({
messageID: e.data.messageID,
result: result
});
} else if (e.data.method === 'debug') {
console.log(e.data.data);
}
});
worker.js
// A simple generic messaging API
var callbacks = {};
var lastMessageID = 0;
addEventListener('message', function(e) {
if (callbacks[e.data.messageID]) {
callbacks[e.data.messageID](e.data.result);
}
});
function sendRequest(method, data, callback) {
var messageID = ++lastMessageID;
if (callback) callbacks[messageID] = callback;
postMessage({
method: method,
data: data,
messageID: messageID
});
}
// Example:
sendRequest('getsrc',
'<img src="foo.png">' +
"<img src='bar.png'>" +
'<textarea><img src="should.not.be.visible"></textarea>',
function(result) {
sendRequest('debug', 'Received: ' + result.join(', '));
}
);
i have for example this URL
www.mypage/SessionPage.aspx?session=session%202#b
using this code i can track the complet URL
_gaq.push(['pageTrackerTime._trackEvent', 'category', 'action', document.location.href, roundleaveSiteEnd]);
BUt i would like only to take part of it like session%202
is there a way to do this in JavaScript
Use regular expression
function getSessionId() {
var re = /session=([^&=]+)/g;
var match = re.exec(document.location.href);
if (match) {
var sessionId = match[1];
return sessionId;
}
return null;
}