最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - JavaScript - Find and replace word in array - Stack Overflow

programmeradmin4浏览0评论

How would I find a word (in this case a placeholder, e.g _ORGAN_) in an array and replace it with an element's value?

sql = new Array();

$('#system').change(function(){
    filter = " topography_index = _ORGAN_";     
    sql.push(filter);
});

In this case I would want to replace _ORGAN_ with $('#organ_menu').val();

How would I find a word (in this case a placeholder, e.g _ORGAN_) in an array and replace it with an element's value?

sql = new Array();

$('#system').change(function(){
    filter = " topography_index = _ORGAN_";     
    sql.push(filter);
});

In this case I would want to replace _ORGAN_ with $('#organ_menu').val();

Share Improve this question edited Mar 5, 2014 at 9:11 IlludiumPu36 asked Mar 5, 2014 at 9:06 IlludiumPu36IlludiumPu36 4,30411 gold badges65 silver badges105 bronze badges 1
  • Do you want to replace in Array element which value is _ORGAN_ ? – nanobash Commented Mar 5, 2014 at 9:14
Add a ment  | 

6 Answers 6

Reset to default 3

Try this:

// sql array
var sql = ['organ not found', '_ORGAN_ is here'];
var val_to_replace = '_ORGAN_';
var replace_with = 'heart'; // temp value - change it with $('#organ_menu').val()

$.each(sql, function (key, val) {
    // search for value and replace it
    sql[key] = val.replace(val_to_replace, replace_with);
})

console.log(sql)

JSFiddle: http://jsfiddle/d8sZT/

You can simply do by iterating the array and then assign the value to once it find its match.

for (i = 0; i < sql.length; i++) {
    if (sql[i] === "_ORGAN_") {
        sql[i] = $('#organ_menu').val();
    }
}

example fiddle for better understanding.

You can simply iterate over the array and use replace on each element

var organValue = $('#organ_menu').val();

for (var i = 0; i < sql.length; i++) {
    sql[i] = sql[i].replace("_ORGAN_", organValue);
}
var regExp = new RegExp(organ, 'g');    
$.each(sql, function(index, value) {
    sql[index] = value.replace(regExp, 'test');
})

I'd try something like this, using replace:

sql = new Array();

$('#system').change(function(){
    filter = " topography_index = _ORGAN_".replace("_ORGAN_", $('#organ_menu').val(), "gi");  
    sql.push(filter);
});

You can do this:

First find the index of the item:

 var index=sql.indexOf("_ORGAN_");

Then insert your new item at that index and remove the first one:

sql.splice(index,1,newitem);

splice

发布评论

评论列表(0)

  1. 暂无评论