简体   繁体   中英

JavaScript - Find and replace word in array

How would I find a word (in this case a placeholder, eg _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();

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.net/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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