How do I replace same character occurrence with different characters - javascript

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.

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)

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

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

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

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/

Related

Return multiple strings from function based on variable number

I have a string
var str = 'string'
I have a multiplier
var mult = 3
I want to return stringstringstring
The mult will change. Basically mult is kind of like a power but this is a string not a number. And I need to return multiple strings. I'm thinking of looping where mult = the number of times to loop and each would conceptually 'push' but I don't want an array or something like =+ but not a number. I'm thinking I could have the output push to an array the number of times = to mult, and then join the array - but I don't know if join is possible without a delimiter. I'm new at javascript and the below doesn't work but it's what I'm thinking. There's also no ability to input a function in the place I'm running javascript and also no libraries.
var loop = {
var str = 'string'
var arr = [];
var mult = 3;
var i = 0
for (i = 0, mult-1, i++) {
arr.push('string'[i]);
}
}
var finalString = arr.join(''); // I don't know how to get it out of an object first before joining
Not sure if what I want is ridiculous or if it's at all possible
You mean something like below,
var str = 'string'
var mult = 3
var str2 = ''
for(i = 0; i < mult; i++) {
str2 += str
}
console.log(str2)
var str = 'string'
var mult = 3;
var sol =""
while(mult--) {
sol +=str;
}
console.log(sol)
Using resusable function:
const concatStr= (str, mult)=>{
var sol =""
while(mult--) {
sol +=str;
}
console.log(sol)
}
concatStr("string",3)
Using the inbuilt Array.from method:
var str = "string"
var mult = 3
var sol = Array.from({length: mult}, ()=> str).join("")
console.log(sol)
function concatString(str, mult) {
var result = ''
for(i = 0; i < mult; i++) {
result = result.concat(str);
}
return result;
}
const value = concatString('string', 3);
console.log(value);
Also you can use array inbuilt methods,
const mult = 3, displayVal = 'str';
Array(mult).fill(displayVal).join('');
// the string object has a repeat method
console.log('string'.repeat(3));

Javascript Array to MySQL "In" list of values

I have an array where each element corresponds to an alphanumeric string, lets say :
userIds : ['Ab526', 'shvx23', '23636dsd']
I want to convert it into such a format so that I can pass this list of strings to IN clause of mySQL query as something like :
Select * from Users where userIds in '(...)';
I tried using array.join() and many other methods, suggested somewhere or the other but all in vain.
var userIds = ['Ab526', 'shvx23', '23636dsd']
var ids = userIds.join(',');
var query = 'Select * from Users where userIds in (' + ids + ')';
console.log(query);
which results in :
Select * from Users where userIds in ('Ab526, shvx23, 23636dsd');
If anyone could suggest a solution as how can I achieve what I want to, it would be of great help.
You could map the quoted values and join later.
var userIds = ['Ab526', 'shvx23', '2363\'6dsd'],
result = userIds.map(function (a) { return "'" + a.replace("'", "''") + "'"; }).join();
console.log(result);
You could use reduce on the array:
var userIds = ['Ab526', 'shvx23', '23636dsd'];
var clause = userIds.reduce(
function (cl , a, currIndex, arr)
{
return cl +
(currIndex == 0 ? "" : ",")
+"'"+ a + "'"+
(currIndex == arr.length-1 ? ")" : "") ; } , "(" );
console.log(clause );
You can use the following code :
var userIds = ['Ab526', 'shvx23', '23636dsd'];
var ids = '';
userIds.forEach(function(entry,index) {
ids += (index == 0) ? entry : ',' + entry;
});
console.log(ids);
Or a simple one liner
const userIds = [12,13,14,15];
const query = `Select * from Users where userIds in ('${userIds.join("','")}')`;
console.log(query)
This worked for me for the same issue:
var myList = [1, 2, 3]
var listAsString = myList.toString()
var queryList = "(" + listAsString + ")"
SQL Query is like so:
WHERE number IN queryList
let tickers = ['AAPL', 'MSFT']
const inStmt = "('" + tickers.join("','") + "')"
This will give you the result inStmt == ('AAPL','MSFT') which can be later on used as:
const QUERY = `select x from Y where Y.z in ${inStmt}`
Please note, that if you have numbers, not strings, single quotes must be removed:
let tickers = [1, 2, 3]
const inStmt = "(" + tickers.join(",") + ")"

Get split number and string from string

I have an array of string like below:
var array =[];
array.push("Complex12");
array.push("NumberCar1");
array.push("Protect5");
I want to split the string and number of each item.
var Id = parseInt(array[0].match(/\d/g));
var type = array[0].replace(/\d+/g, '');
But I only get Id = 1(I want 12) and type = "Complex", where am I wrong?
thanks
I think you just missed + in first regexp
var Id = parseInt(array[0].match(/\d+/g));
Do it in one pattern with capture groups:
var mystr = "Complex12";
if (m = mystr.match(/^([a-z]+)([0-9]+)$/i)) {
var type = m[1];
var id = m[2];
}

Find text between two characters and for each, do something

I have a file full with text in the following format:
(ignoring the fact that it is CSS) I need to get the string between the two | characters and each time, do something:
<div id="unused">
|#main|
#header|
.bananas|
#nav|
etc
</div>
The code I have is this:
var test_str = $('#unused').text();
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
//I want to do something with each string here
This just gets the first string. How can I add logic in there to do something for each string?
You can use split method to get array of strings between |
Live Demo
arr = $('#unused').text().split('|');
You can split like
var my_splitted_var = $('#unused').text().split('|');
One way;
$.each($("#unused").text().split("|"), function(ix, val) {
val = $.trim(val); //remove \r|\n
if (val !== "")
alert(val);
});
One way :
var test_str = $('#unused').text();
while(!test_str.indexOf('|'))
{
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
test_str = test_str.slice(end_pos,test_str.length);
}
RegExp-Version:
LIVE DEMO (jsfiddle.net)
var trimmedHtml = $("#unused").html().replace(/\s/g, '');
var result = new Array();
var regExp = /\|(.+?)(?=\|)/g;
var match = regExp.exec(trimmedHtml);
result.push(match[1]);
while (match != null) {
match = regExp.exec(trimmedHtml);
if (match != null) result.push(match[1]);
}
alert(result);
So you only get the elements BETWEEN the pipes (|).
In my example I pushed every matching result to an array. You can now iterate over it to get your result.

remove all empty values from url

I want to remove all empty values from an url:
var s="value1=a&value2=&value3=b&value4=c&value5=";
s = s.replace(...???...);
alert(s);
Expected output:
value1=a&value3=b&value4=c
I only need the query part of the URL to be taken into account.
Something like this:
s = s.replace(/[^=&]+=(&|$)/g,"").replace(/&$/,"");
That is, remove groups of one or more non-equals/non-ampersand characters that are followed by an equals sign and ampersand or end of string. Then remove any leftover trailing ampersand.
Demo: http://jsfiddle.net/pKHzr/
s = s.replace(/[^?=&]+=(&|$)/g,"").replace(/&$/,"");
Added a '?' to nnnnnn's answer to fix the issue where the first parameter is empty in a full URL.
This should do the trick:
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmp = s.split('&')
var newS = '';
for(var i in a) {
var t = a[i];
if(t[t.length - 1] !== '=') {
newS += t + '&';
}
}
if(newS[newS.length - 1] === '&') {
newS = newS.substr(0, newS.length - 1);
}
console.log(newS);
I don't find any solution to do that with one Regex expression.
But you could loop through your string and construct a new result string : http://jsfiddle.net/UQTY2/3/
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmpArray = s.split('&');
var final = '';
for(var i=0 ; i<tmpArray.length ; i++)
if(tmpArray[i].split('=')[1] != '')
final += tmpArray[i] + '&';
final = final.substr(0,final.length-1)
alert(final)
Where do you take all the values?
I suggest using an array:
function getValues(str){
var values = [];
var s = str.split('&');
for(var val in s){//source is a
var split = val.split('=');
if(split [1] != '' && split [1] != null){
values.push(val);
}
}
return values.join('&');
}

Categories