Saurabh Sharma
Saurabh Sharma

Reputation: 503

How do I replace same character occurrence with different characters

I have a string like:

my_str = "select * from users where id = ? and name = ?;"

I also have an array to replace '?'

var arr = [1,'test']

I wanted to replace first ? with 1 and second ? with 'test' in jQuery/JavaScript dynamically. There can be a number of ? in string.

Note this question has no relation with MySQL the query I have written is just a string.

Upvotes: 1

Views: 220

Answers (5)

Ganesh Putta
Ganesh Putta

Reputation: 2681

Using the replace function you can do that, just use replace multiple times to replace both '?'.

var my_str = "select * from users where id = ? and name = ?;"
var arr = [1,'test']
my_str = my_str.replace("?",arr[0]).replace("?",arr[1]);
console.log(my_str);

Upvotes: 1

jotch
jotch

Reputation: 6916

For a more dynamic option, where replace is an array containing the replacements in order:

const string = 'select * from users where id = ? and name = ?;'
const replace = [1, 'test']

let index = 0
const output = string.replace(/\?/g, () => replace[index++])
console.log(output)

Upvotes: 4

Navneeth
Navneeth

Reputation: 988

use replace method multiple times for replacing.

var my_str = "select * from users where id = ? and name = ?;"

my_str = my_str.replace("?","1"); //replaces first "?"

my_str = my_str.replace("?","test"); //replaces second "?"

alert(my_str);

Upvotes: 2

Sunny
Sunny

Reputation: 96

Get index of ? and put into a array, then write a function to replace.

    var str = "select * from users where id = ? and name = ?;"
    var indices = [];
    for(var i=0; i<str.length;i++) {
        if (str[i] === "?") indices.push(i);
    }
    str = replaceAt(str,0,"1");
    str = replaceAt(str,1,"Jonh");
    alert(str);
    
    function replaceAt(str, index, replacement) {
    	return str.substr(0, indices[index]) + replacement+ str.substr(indices[index] + 1, str.length);
    }

https://jsfiddle.net/vuph31/hgbms2s1/1/

Upvotes: 0

fab
fab

Reputation: 1259

use replace() multiple times

var r = "select * from users where id = ? and name = ?;".replace("?", '1').replace('?','test');
console.log(r);

and if you have an array of values to replace the '?':

var arr = [1,'test']
var r = "select * from users where id = ? and name = ?;"
for(i=0; i<arr.length; i++){
  r = r.replace('?',arr[i]);
}
console.log(r);

Upvotes: 0

Related Questions