简体   繁体   English

Javascript将字符串的一部分替换为变量

[英]Javascript replace parts of string to variables

I wish to do a search and replace in a string. 我希望进行搜索并替换为字符串。 It searches for any word that begins with "$" and replaces it with a value from an array. 它搜索以“ $”开头的任何单词,并将其替换为数组中的值。 For example if the string is: 例如,如果字符串是:

[div class='news'][h4]$title[/h4][p]$desc[/p][/div]

It replaces [] to <> (already done). 它将[]替换为<>(已完成)。 But then i want it to replace $title with data from an array. 但是然后我希望它用数组中的数据替换$ title。 So data["title"] and then $desc would be replaced with data["desc"]. 因此,data [“ title”]和$ desc将替换为data [“ desc”]。 The code i have so far is 我到目前为止的代码是

var obj = $('#'+id);
var url = $(obj).attr('loadJSON');
var format = $(obj).attr('responseFormat');
$.getJSON(url, function(data) {
    var html = "";
    for(var i=0;i<data.length;i++) {
        var tmp = format;
        tmp = tmp.replace(/\[+(.*?)\]+/g,"<$1>");
        tmp = tmp.replace();
    }
});

The format is the string which it will replace in, and data (from the JSON response) is the array which i want the variables to change to. 格式是将替换的字符串,数据(来自JSON响应)是我希望变量更改为的数组。

Could someone please help me with this? 有人可以帮我吗? Thanks in advance 提前致谢

then add as last replacement 然后添加为最后一个替换

tmp = tmp.replace(/\$([a-z]+)/gi, function(match, v) {
   return data[v] || v;
})

note that in case of data[v] is undefined you could return something else like data[v] || ["not found", v].join(' ') 请注意,在data[v]未定义的情况下,您可以返回其他内容,例如data[v] || ["not found", v].join(' ') data[v] || ["not found", v].join(' ') just to track what variable is missing data[v] || ["not found", v].join(' ')只是为了跟踪缺少什么变量

I'm no JS expert, but this looks wrong in so many ways... your data object should be a JS object, that is something like { title: 'Generic title.', description: 'It's a generic title' } . 我不是JS专家,但是从很多方面来看这都是错误的...您的数据对象应该是JS对象,类似于{ title: 'Generic title.', description: 'It's a generic title' }

Why not put the values into paragraph elements, and then insert those into the div (ie, you append them). 为什么不将这些值放入段落元素,然后将其插入div(即,将它们附加)。 Something like this: 像这样:

$.getJSON(url, function(data) {
    $('div.news').append($('<p />').text(data.title));
    $('div.news').append($('<p />').txt(data.description));
});

You could do 你可以做

tmp = tmp.replace(/\$([a-z]+)/gi, function(match) {
    match = match.replace('$', '');
   return (data[match] || match)
});

http://jsfiddle.net/uZbk8/ http://jsfiddle.net/uZbk8/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM