Change data inside string with box brackets - javascript

I have a string
garments[0][1]; // The 0 and 1 can be other numbers
I need to replace the data inside the second and the third box brackets.
[0] and [1]
So that it can be
garments[4][6]
Please let me know your suggestions when you get a chance, thank you.

You can try that:
var string = 'garments[' + 4 + '][' + 6 + ']'; //in your onClick function
//To increment dynamically:
var string = 'garments[' + i + '][' + j + ']'; //i and j being variables incrementing in your loops/treatments
Update to address comments:
If you want to break "garnments[0][1]" into "garnments",0 and 1 you can do the following:
var string = "garnments[0][1]";
string = string.split('['); //string = [["garnments"],["0]"],["1]"]]
string[1].replace(']','');
string[2].replace(']',''); //string = [["garnments"],["0"],["1"]]
You can then change values and rebuild your string for further use.
It is a bit brutal though. You can use RegExp as showed by #Diego

You can use String.prototype.replace()
'garments[0][1]'.replace('[0]','[4]').replace('[1]','[6]')

For any possible string with ***[m][n] format:
Function SetNewValues(testString, n, m)
{
var keyWordLengh = testString.indexOf("[");
return testString.substring(0,keyWordLengh) + "[" + n.toString() + "][" + m.toString() + "]";
}
Where:
testString is entire string to work on, like "something[342][345]"
n,m are values to be put inside brackets :)

This would be my approach.
var string = "['foobar'][2][12]";
var match =
/\[([^\]]+)\](?:\[(\d+)\])(?:\[(\d+)\])/g
.exec(string);
console.log(match);

Related

How to get the entire string until the + sign that changes in length?

I have a react app that gets a value from an API that looks like this: "Blahblah + blahblah" or "Blah blah + ..." (basically the value preceding the + sign can be one or several words, but the consistency is it is always followed by a space and + sign). How do I use this value and parse only the text that precedes the + sign so I can use it?
Thanks!
var x = "Blahblah + blahblah".split('+')[0]
console.log (x) // prints => Blahblah
x = "abc + def".split('+')[0]
console.log (x) // prints => abc
You can use JavaScript's .split() function to split it like this:
const splitString = string.split(" +")
This will return an array of substrings of the first string, the first element of which will be there first part of the string before the " +", which you can access by calling splitString[0].
https://www.w3schools.com/jsref/jsref_split.asp
Above peoples already give u answer,if u want to avoid white space just trim splitted String
var str = "Blahblah + blahblah+Blahblah + blahblah";
var res = str.split("+");
for(var i=0;i<res.length;i++)
{
console.log(res[i].trim());
}
Please see the code below:
var x = "Blahblah + blahblah".split('+');
var result = '';
for(let i of x)
{
result += i.trim();
}
console.log(result);

Adding quotes to a comma separated string

What I have:
var a = "1.1.1.1,2.2.2.2,3.3.3.3"
What I need:
var a = '1.1.1.1','2.2.2.2','3.3.3.3'
What I'm trying:
var a = "1.1.1.1,2.2.2.2,3.3.3.3"
var b = a.split(",")
var c
for (var i=0;i<b.length; i++)
{
c.concat("\'").concat(b[i]).concat("\',\"")
}
What I'm actually getting with the above
"'1.1.1.1','"
I'm only able to get the first element right, how do I rectify this?
Also, in JS, is it even possible to have something like '1.1.1.1','2.2.2.2','3.3.3.3' stored in a variable?
A background to this problem:
I have an iframe whose source is a kibana query. The query in fact takes in values to a particular parameter in the above mentioned format.
Eg:
params:!('1.1.1.1','2.2.2.2')
While my db contains the param values as a string of CSV.
Eg.
"1.1.1.1,2.2.2.2,3.3.3.3"
Try this
var a = "1.1.1.1,2.2.2.2,3.3.3.3";
var b = "'" + a.split( "," ).join( "','" ) + "'";
console.log( b );
You don't need to deal with iterations for this, use a RegExp replace:
var a = "1.1.1.1,2.2.2.2,3.3.3.3";
var b = "'" + a.replace(/,/g, "','") + "'";
console.log( b );
The naive solution to your problem looks like this:
> line = '1.1.1.1,2.2.2.2,3.3.3.3'
'1.1.1.1,2.2.2.2,3.3.3.3'
> '"' + line.replace(/,/g, '","') + '"'
'"1.1.1.1","2.2.2.2","3.3.3.3"'
or if the quotes need to be reversed:
> "'" + line.replace(/,/g, "','") + "'"
'\'1.1.1.1\',\'2.2.2.2\',\'3.3.3.3\''
However, it sounds like what you need is a full-blown CSV parser, to handle cases in which you have quotes and commas and new lines and other crazy characters embedded in your input.
The naive solution seems to be in line, though, with what you were trying to do, and might illustrate why your approach fell short.
Your code works as you intended. Can you append to c without declaring?
var a = "1.1.1.1,2.2.2.2,3.3.3.3"
var b = a.split(",")
var c = ""
for (var i=0;i<b.length; b++)
{
c.concat("\'").concat(b[i]).concat("\',\"")
console.log(b)
}
You can store several values in a variables by using array for example.
If you want to get string like '"1.1.1.1","2.2.2.2","3.3.3.3"' you can use the following code:
var a = "1.1.1.1,2.2.2.2,3.3.3.3";
var b = a.split(',').map(function (str) {
return '"' + str+ '"';
}).join(',');
console.log(b);

How can I change the text in just a part of my string with javascript?

I have a javascript string that contains the following:
data-href="/Admin/Edit?pk=0001I&rk=50050055"
How can I change this string so the value of rk is changed to a value held in the string newRowKey? Not sure if it helps but the data format always looks like this with the rk followed by an = and then terminated with the "
datahref="/Admin/Edit?pk=0001I&rk=50050055";
to change it if your building the URL
datahref="/Admin/Edit?pk=0001I&rk="+ newRowKey;
or replace it if you know the existing value
datahref.replace("50050055", newRowKey);
if you do not know the value of rk, but you know its last in the URL, you could use indexOf to find it.
datahref = datahref.substring(0,datahref.indexOf("rk=")+3) + newRowKey;
Maybe you want a regular expression to replace that rk.
newRowKey = 'XXXXXX'
s = 'Edit?pk=0001I&rk=50050055';
s2 = s.replace(/(.*;)(rk=)(.*)(&|)/, '$1$2' + newRowKey)
alert( s + "\n" + s2 );
//2nd test
s = 'Edit?pk=0001I&rk=50050055&';
s2 = s.replace(/(.*;)(rk=)(.*)(&|)/, '$1$2' + newRowKey)
alert( s + "\n" + s2 );
​demo: http://jsfiddle.net/fedmich/g3TjE/
data_href.replace(/rk=.*$/,'rk=' + newRowKey);

javascript regex to replace a substring

In javascript, how would I use a regular expression to replace everything to the right of "Source="
Assume, for example:
var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSoruceValue="http://acme.com/vegiePage.aspx"
Goal is to get this value in outStr:
var outStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/vegiePage.aspx"
Thanks!!
Assumes that source= will always be at the end
var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSourceValue="http://acme.com/vegiePage.aspx"
var outStr = inStr.replace( /(Source=).*/, "$1" + newSourceValue);
Is "Source" always linked to the first occurrance of "&"?
You could use
indexOf("&") + 7
(number of letters in the word "Source" + one for "=").
Then create the new string by appending the new source to the substring using the index from before.
string.replace( /pattern/, replace_text );
var outStr = inStr.replace( /&Source=.*$/, "&Source=" + newSoruceValue );
or
var outStr = inStr.replace( /(&Source=).*$/, "$1" + newSoruceValue )

How to prevent values from being converted to strings in javascript?

var str;
var displayedNum;
for (i in imgURLArray){
str = "<li photonum="+i+">" + "<a>"+ (1+i) + "</a>" + "</li>";
$("ul.selection-list").append(str);
}
I need to do this within a loop, but what happens is it prints out "11" instead of "2", because it converts to string before addition.
I have the same problem if I try to do the addition outside of the string and store in a variable as well, it still converts to string instead of doing addition.
Number(1+1) still converts to string first before turning it into a number, so it comes out 11.
Use parenthesis:
var str = "foobar" + (1+i) + "other stuff";
I have the same problem if I try to do the addition outside of the string and store in a variable as well, it still converts to string instead of doing addition.
It should not. My guess is that you are doing something wrong there too.
Update: It seems you are converting i to a string somewhere in the code you did not post.
Update 2: Don't use for..in to loop over an array. Use a normal for loop if it is really an array:
for(var i = 0, l = imgURLArray.length; i < l; i++)
But if it is an objects:
for...in will always set i as a string (as it loops over the properties of the object which are not always integers) . That means you would have to convert i before you do any addition:
... + (1 + (+i)) + ...
Update 3:
You don't always have to use such an "explicit" for loop. For example, you can traverse the array in reverse order, which makes the head shorter:
for (var i = imgURLArray.length; i--; ) {
str = "<li photonum="+i+">" + "<a>"+ (1+i) + "</a>" + "</li>";
$("ul.selection-list").prepend(str);
}
Try wrapping numbers in Number()
Like:
var i = 1;
var str = "foobar" + Number(1+i) + "other stuff";
var str = "foobar" + (1+i) + "other stuff";
You could just use the parseInt method:
var str = "foobar" + (parseInt(1+i)) + "other stuff";
The reason is due to your loop:
for (i in imgURLArray){
This iterates over all the property names of imgURLArray as strings. So you will need to use Number() to convert i to an integer:
str = "<li photonum="+i+">" + "<a>"+ (1+Number(i)) + "</a>" + "</li>";

Categories

Resources