IlludiumPu36
IlludiumPu36

Reputation: 4304

JavaScript - Find and replace word in array

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();

Upvotes: 0

Views: 8208

Answers (6)

Mohit Pandey
Mohit Pandey

Reputation: 3813

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/

Upvotes: 3

jansesun
jansesun

Reputation: 108

var regExp = new RegExp(organ, 'g');    
$.each(sql, function(index, value) {
    sql[index] = value.replace(regExp, 'test');
})

Upvotes: 1

Johan
Johan

Reputation: 1026

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);
}

Upvotes: 1

Somnath Kharat
Somnath Kharat

Reputation: 3610

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

Upvotes: 0

Praveen
Praveen

Reputation: 56509

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.

Upvotes: 1

Lorenzo Marcon
Lorenzo Marcon

Reputation: 8169

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);
});

Upvotes: 0

Related Questions