Reb*_*one 7 javascript regex ajax
我有一个包含ajax调用的函数:
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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
我叫它:
example("http://www.example.com", function(result) {
// do something with result
})
Run Code Online (Sandbox Code Playgroud)
但是,我想example()
在这种情况下使用:
text.replace(/[regex not shown]/g, function(){
return RegExp.$1 + example(RegExp.$2); // does not work
});
Run Code Online (Sandbox Code Playgroud)
即,正则表达式找到多个匹配,然后我添加example([whatever it matched])
.有没有办法整合
example("http://www.example.com", function(result) {
// do something with result
})
Run Code Online (Sandbox Code Playgroud)
进入text.replace()
?
先感谢您!
创建一个函数来进行 ajax 调用并处理正则表达式上的匹配项替换。根据您上面提供的内容,假设您想要多次执行这些类型的替换,这是最模块化的方法。
function replaceTextAfterAjax(str, regex, matchSendToServer, fn) {
var matches = regex.exec(str);
var externUrl = matches[matchSendToServer];
$.ajax({
type: "GET",
url: externUrl,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(json) {
fn(json.serverSideReplaceText, matches);
},
})
}
var text = "go to http://www.example.com";
replaceTextAfterAjax(text, /(go to) (.*)$/, 2, function(response, matches) {
text = matches[1] + ' ' + response;
// continue to use `text`
});
Run Code Online (Sandbox Code Playgroud)
请注意,您应该通过调用exec
正则表达式实例来保持对 RegExp 的本地使用。这可以使您的代码保持线程安全,并防止其他方法获取另一个调用的 RegExp.$N 值。
归档时间: |
|
查看次数: |
355 次 |
最近记录: |