I have a challenge that I am trying to solve and cannot seem to come up with a solid solution.
I have 3 records like this:
"a,b,c,d,e","1,2,3,4,5","record 1"
"f,g,h,i","11,12,15,16","record 2"
"x,y,z","19,20,21","record 3"
Looking to create this output
"a,1"
"b,2"
"c,3"
"d,4"
"e,5"
...
...
"y,20"
"z,21"
How would I go about this using java-script or
I have have worked out how to separate each string but collecting both substrings and looping through seems to be a challenge.
This can get a little bit Tricky if you dont have a constant format.
In this example i have two strings and each sub-string is separated by ",".
Also both strings should be the same length.
I return the result as an array here. You can append it to a existing string instead.
s1 = "1,2,3,4,5";
s2 = "a,b,c,d,e";
s3 = [];
for(i=0; s1.length>i;i++){
if(s1[i] != ","){
s3.push(s1[i]+","+s2[i]);
}
}
console.log(s3);
Since im not sure if i did understand the Question correctly...
If you dont understand something or the answer is not what you excepted, let me know in the comments and i will try to adapt to it.
Related
This question already has answers here:
Template literal inside of the RegEx
(2 answers)
Closed 1 year ago.
hi I am coding an online shop ,
currently working on add to cart functionality,
like to store product ids and their quantity in a cookie like this id1:qt1,id2:qt2...
like to check if a product is already is in cart , looks like my regular expr doesn't work
const reg = new RegExp(`${product_id}:\d+`);
if (!reg.test(cart_cookie)){
const values = cart_cookie.split(',');
values.push(`${product_id}:1`);
setCookie('cart', values.join(','), 7);
}
else {
console.log('already in cart.')
}
Yep, your regex is off :)
It stumped me for a second, but its clear when you check what your "regex" string actually evaluates to: /product_id:d+/. This is because the string you're passing in sees the \d as a literal d. To fix this, just throw another \ in there so the original \ is whats being escaped. Before, you were matching things like "apple:ddddddd".
Once you do that, your code DOES seem to work, but maybe just not like you expect it to?
I've put your code into a function, since you would -- presumably -- be calling this every time you want to add an item to the cart, and added a console.log statement to show the end value of the "cookie."
// Just as a stand in for actual values
let cart_cookie = 'apples:2,oranges:3,bananas:1';
function addCartItem(product_id) {
const reg = new RegExp(`${product_id}:\\d+`);
console.log(reg)
if (!reg.test(cart_cookie)){
const values = cart_cookie.split(',');
values.push(`${product_id}:1`);
console.log('cart_cookie is now ', values.join(','));
setCookie('cart', values.join(','), 7);
}
else {
console.log('already in cart.')
}
}
addCartItem('apples');
// already in cart.
addCartItem('kiwis');
// cart_cookie is now apples:2,oranges:3,bananas:1,kiwis:1
Its fixed! 🥳 But...
I'm not quite sure what your product ids look like, but if they contain special characters (e.g. periods, question marks, etc.) it'll cause some issues with how your regex performs. I doubt you have things like question marks in it, but something like this illustrates my point:
let cart_cookie = '123.15:3,2.5.141:1';
/* ... */
addCartItem('1.3.15');
// already in cart.
I know, its a rather unlikely scenario -- and it might not even apply to you if you know your product ids won't contain anything tricky -- but if you're goal is to build an online shop, you'll probably want to cover all your bases.
Even fixing that, this still has a potential issue, as this will only let you add a quantity of 1 to an item thats not already in the cart, with no ability to increment it after that. Not sure if thats what you're going for.
This veers off of the main question you posed, but a potentially better solution might be using the browser's localstorage (or sessionstorage) to keep track of the cart. This would allow you to use more familiar data structures to store this info, rather than a string that you have to pray you're parsing correctly.
More info on that here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
you can use just array method instead you don't need for regex for that,
for example..
const values = cart_cookie.split(',');
values.foreach(value => {
if(value != product_id){
values.push(`${product_id}:1`);
setCookie('cart', values.join(','), 7);
}
});
I am learning JavaScript and I see %value% in a code but I do not know what does it mean or how to use it. Can anyone please help me explain to me. Thank you very much.
var formattedLocation = HTMLworkLocation.replace("%data%", work.jobs[job].location);
"%data%" is just a literal string. This code will take the value of HTMLWorkLocation, look for the first occurrence of %data% in it, and replace that with the value of work.jobs[job].location, and store the resulting string in formattedLocation.
var work = {
jobs: [{
location: "Home office"
}]
};
var job = 0;
var HTMLworkLocation = "John is located at %data%";
var formattedLocation = HTMLworkLocation.replace("%data%", work.jobs[job].location);
console.log(formattedLocation);
This is probably part of a template system that's used to replace placeholders like %data% with values that come from a table.
You're using string.replace which takes a string or regular expression as it's first argument. Based on the code you posted it looks like you're looking for the string "%data%" (or whatever string you're looking for) in HTMLworkLocation and replacing it with the value in work.jobs[job].location. Then it is being stored in formattedLocation.
I would put a debugger; line after that line of code so you can see what the values are in the debugger console. That might help make more sense of things.
Here is more info on the str.replace method with some examples
In application that I'am working on I have dynamically generated UI it is number of controls and listed entries depends on records from DB.What I'am trying to achieve is to write RegEx that would help me extract some numbers assigned as part of controls ID.
The way how I'am assigning IDs is : cText+(row that it represents in its group)+G+(group number).For example cText4G12
What I'am looking for is to get from that ID what Row it represents in example is 4 and it's group 12. I've never used RegEx before so I'am asking for your help :)
RegEx is not something that is easy to get your head around, so I would strongly recommend that you spend a bit of time to learn it - as it will be beneficial to you in the long run.
However, against my best judgement - here is code that will get you what you need..
var id = "cText4G12";
var result = id.match(/^cText(\d+)G(\d+)$/);
result[1] will contain "4"
result[2] will contain "12"
You don't really need regex. You can simply do:
var my_id = "cText4G12";
var row = my_id.slice(my_id.indexOf("cText")+5,my_id.indexOf("G"));
var group = my_id.slice(my_id.indexOf("G")+1);
Found some things like in Visual Basic but not Javascript and exactly what I'm trying to do. It's a tad bit different. I'm trying to figured out how to rearrange characters in a string, it's in a for loop as well in order to cut the string in half. Now I need to rearrange that.
First I have:
12345678910111213141516
then in the for loop
12345678
I'm trying fix it so now I get
72648531
But I have to do it in a way so people can't read the code and know that there's 8 characters at this point in the string without hard work and trouble. My for loop is also jumbled up and screwy so it can't be figured out. Something like this. I really cannot post the code though.
var con = "";
for (var i = complex math that equals 0; i < complex math to equal 8; i++) {
var newStr = word[i]; // I need it to come out to the rearranged somewhere close by
var con = con+""+newStr;
}
Two commonly used techniques come to mind:
A common approach to things is by doing some XOR calculations: Look at this unrelated examples:
http://www.javascriptsource.com/passwords/xor-encryption4.html
Extracting information from page with Jsoup
You can use tools like http://www.javascriptobfuscator.com/Default.aspx to make it harder for people to figure your code.
I want to find anything that comes after s= and before & or the end of the string. For example, if the string is
t=qwerty&s=hello&p=3
I want to get hello. And if the string is
t=qwerty&s=hello
I also want to get hello
Thank you!
\bs=([^&]+) and grabbing $1should be good enough, no?
edit: added word anchor! Otherwise it would also match for herpies, dongles...
Why don't you try something that was generically aimed at parsing query strings? That way, you can assume you won't run into the obvious next hurdle while reinventing the wheel.
jQuery has the query object for that (see JavaScript query string)
Or you can google a bit:
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
looks useful; for example with
http://www.bloggingdeveloper.com?author=bloggingdeveloper
you want to get the "author" querystring's value:
var author_value = getQuerystring('author');
The simplest way to do this is with a selector s=([^&]*)&. The inside of the parentheses has [^&] to prevent it from grabbing hello&p=3 of there were another field after p.
You can also use the following expression, based on the solution provided here, which finds all characters between the two given strings:
(?<=s=)(.*)(?=&)
In your case you may need to slightly modify it to account for the "end of the string" option (there are several ways to do it, especially when you can use simple code manipulations such as manually adding a & character to the end of the string before running the regex).