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

1
  • Do you want to replace in Array element which value is _ORGAN_ ? Commented Mar 5, 2014 at 9:14

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

1 Comment

This works OK, but replaces only the first instance of ORGAN
1
var regExp = new RegExp(organ, 'g');    
$.each(sql, function(index, value) {
    sql[index] = value.replace(regExp, 'test');
})

1 Comment

This works great when replacing multiple instances, so your solution givesme some flexibity...I'll probably use this...many thanks!
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.