I have a function containing an ajax call:
function example(param, callback) {
$.ajax({
type: "GET",
url: param,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(data) {
// do something with data
callback(data);
}
});
}
I call it by:
example("http://www.example.com", function(result) {
// do something with result
})
But, I'd like to use example()
in this context:
text.replace(/[regex not shown]/g, function(){
return RegExp.$1 + example(RegExp.$2); // does not work
});
i.e., the regex finds multiple matches, to which I then add example([whatever it matched])
. Is there a way to integrate
example("http://www.example.com", function(result) {
// do something with result
})
into the text.replace()
?
Thank you in advance!
You can't. That's because you are passing a to the .replace() method a function literal, so the replace method will take that function .toString() returned string (its source code) as an argument.
That is because .replace() method is synchronous and don't expect a callback as second argument, but a string, so it will convert any second argument to string if is not.
And if you actually call the function in the parameter, cause your function has no defined return value will parse "undefined" as second value.
But you can write your own asynchronous replace method and add it to the String prototype. I can't edit code in my phone, so when I get back to my computer I write it for you if you haven't figured out.
Edit:
Actually I was wrong, you can use a callback in the replace method. The problem is the way you are using an asynchronous call inside there. I don't know what are you exactly trying to do, so I hope this help you.
String.prototype.myReplace=function(re, o, p){
var v=[];
var t=this;
t.toString().replace(re, function(m){
if(m==RegExp.$1){v[1]=m;};
if(m==RegExp.$2){v[2]=m;};
});
$.ajax({
type: "GET",
url: v[2],
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(data) {
// do something with data
o[p]=t.toString().replace(re, function(m){
if(m==RegExp.$1){return v[1];};
if(m==RegExp.$2){return data.toString();};
});
}
});
};
And call it like this:
text.myReplace(/[regex not shown]/g, this/* or whatever object is */, 'text'});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With