loop through json object and check if URL ends in certain value - javascript

for(var j=0; j<product.image_groups[0].images.length; j++){
console.log("images in json" + product.image_groups[0].images[j].link)
}
This product.image_groups[0].images[j].link returns a a URL for example:
http://images.domain.com/is/image/domain/hbeu50274296_021_11
http://images.domain.com/is/image/domain/hbeu50274296_021_10
http://images.domain.com/is/image/domain/hbeu50274296_021_21
Within the loop I want to save only the URL that ends in _21 into a variable not sure how I would do this. I guess with a regex but how exactly?

Use string.match function. The below match function will match the string only if it end's with a _21 substring. $ asserts that we are at the end of a line.
for(var j=0; j<product.image_groups[0].images.length; j++){
if (product.image_groups[0].images[j].link.match(/_21$/)) {
console.log("images in json" + product.image_groups[0].images[j].link)
}
}
OR
Use regex.test function.
for(var j=0; j<product.image_groups[0].images.length; j++){
if (/_21$/.test(product.image_groups[0].images[j].link)) {
console.log("images in json" + product.image_groups[0].images[j].link)
}
}
Example:
var l = ["http://images.domain.com/is/image/domain/hbeu50274296_021_11","http://images.domain.com/is/image/domain/hbeu50274296_021_10","http://images.domain.com/is/image/domain/hbeu50274296_021_21"];
for (i=0;i<l.length;i++) {
if(l[i].match(/_21$/)) {
console.log(l[i])
}
}
Output:
http://images.domain.com/is/image/domain/hbeu50274296_021_21

You can reduce the list of images into new list, on given requirement. The easiest way to check, as for me - simply using indexOf method.
var images = product.image_groups[0].images;
var results = images.reduce(function (list, url) {
if (url.indexOf('_21') === url.length - 3) {
list.push(url);
}
return list;
}, []);
// use results here

You could split the url by _ and check the last value to see if it's 21. Something like this:
for (var j = 0; j < product.image_groups[0].images.length; j++) {
var finalPart = product.image_groups[0].images[j].link.split('_').pop();
if (finalPart == '21') {
// do something...
}
}

Try that, clean, simple and fast.
var allImages = product.image_groups[0].images;
for ( //make a for to get all images
var j
in allImages
) {
if (allImages[j].link.slice(-2) == "21") { //check if last 2 characters are "21";
console.log("images in json" + allImages[j].link);
}
}

Related

Perform a merge on two strings

I'm trying to build a collaborative doc editor and implement operational transformation. Imagine we have a string that is manipulated simultaneously by 2 users. They can only add characters, not remove them. We want to incorporate both of their changes.
The original string is: catspider
The first user does this: cat<span id>spider</span>
The second user does this: c<span id>atspi</span>der
I'm trying to write a function that will produce: c<span id>at<span id>spi</span>der</span>
The function I've written is close, but it produces c<span id>at<span i</span>d>spider</span> codepen here
String.prototype.splice = function(start, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start);
};
function merge(saved, working, requested) {
if (!saved || !working || !requested) {
return false;
}
var diffSavedWorking = createDiff(working, saved);
var diffRequestedWorking = createDiff(working, requested);
var newStr = working;
for (var i = 0; i < Math.max(diffRequestedWorking.length, diffSavedWorking.length); i++) {
//splice does an insert `before` -- we will assume that the saved document characters
//should always appear before the requested document characters in this merger operation
//so we first insert requested and then saved, which means that the final string will have the
//original characters first.
if (diffRequestedWorking[i]) {
newStr = newStr.splice(i, diffRequestedWorking[i]);
//we need to update the merge arrays by the number of
//inserted characters.
var length = diffRequestedWorking[i].length;
insertNatX(diffSavedWorking, length, i + 1);
insertNatX(diffRequestedWorking, length, i + 1);
}
if (diffSavedWorking[i]) {
newStr = newStr.splice(i, diffSavedWorking[i]);
//we need to update the merge arrays by the number of
//inserted characters.
var length = diffSavedWorking[i].length;
insertNatX(diffSavedWorking, length, i + 1);
insertNatX(diffRequestedWorking, length, i + 1);
}
}
return newStr;
}
//arr1 should be the shorter array.
//returns inserted characters at their
//insertion index.
function createDiff(arr1, arr2) {
var diff = [];
var j = 0;
for (var i = 0; i < arr1.length; i++) {
diff[i] = "";
while (arr2[j] !== arr1[i]) {
diff[i] += arr2[j];
j++;
}
j++;
}
var remainder = arr2.substr(j);
if (remainder) diff[i] = remainder;
return diff;
}
function insertNatX(arr, length, pos) {
for (var j = 0; j < length; j++) {
arr.splice(pos, 0, "");
}
}
var saved = 'cat<span id>spider</span>';
var working = 'catspider';
var requested = 'c<span id>atspi</span>der';
console.log(merge(saved, working, requested));
Would appreciate any thoughts on a better / simpler way to achieve this.

Create array based on instance of delimiter/square-brackets

I have a string and I wanna create an array with even occurrence of "[]"
"Match[0][a][5][b][0][d][2]"
I want to split them and make an array using this string on the basis of instance of "[]". Each element of the array must have 2 occurrence of "[]" and the next element has two more occurrence of"[]". In another words I wanna create an array with even occurrence of "[]"
I want to make an array from string like:
["Match[0]['a']", "Match[0]['a'][5]['b']", "Match[0]['a'][5]['b'][0]['d']"]
Using javascript/jQuery
I have tried match but I only got it as far as this.
// ['part1.abc', 'part2.abc', 'part3.abc', 'part4']
'part1.abc.part2.abc.part3.abc.part4'.match(/[^.]+(\.[^.]+)?/g);
You can get the individual pieces in your array and then manipulate the result until it has the form you want. An example could be this one:
var str = "Match[0][a][5][b][0][d][2]";
var result = [];
str.split(/[\]\[]{1,2}/).slice(0,-1).reduce(function(acc,item, index) {
acc += '[' + (isNaN(item) ? "'" + item + "'" : item) + ']';
if (index %2 === 0 && index !== 0) {
result.push(acc);
}
return acc;
});
console.log(result) // ["Match[0]['a']", "Match[0]['a'][5]['b']", "Match[0]['a'][5]['b'][0]['d']"]
You can get each bracket with match(/\[.\]/g) and then composes your arrays by adding two by two.
var matches = "Match[0][a][5][b][0][d][2]".match(/\[(.)\]/g);
var result = [];
for (var i = 0; i < matches.length; i += 2) {
var brackets = '';
for(var j = 0; j< i; j++) {
brackets += matches[j];
}
result.push("Match" + brackets);
}
result.shift();
Wow its fun :) ... trying api and see how everyone is solving it. This is what i tried see if this is helpful.
str = "STR[1][3][4d][re]"
var re=/\[\w+\]/g;
var mat = str.match(re);
var ar = [];
for(i=2; i<= mat.length; i=i+2){
ar[ar.length] = "STR" + mat.slice(0,i).join("")
}
console.dir(ar)

if array values exist in a string (similar to regex)

How can I determine if a string contains one of the values from an array?
For example:
var a = ["abc","def","ghi"];
var s = "jskljfdkljflkjk abc jskfdjklsj";
for(var i=0;i<a.length;i++){
if(/a[i]/.test(s)) alert(1);
}
This obviously doens't work... I know it's very possible though hahaha
Your syntax for creating the regular expression is incorrect. That regex will only return true for a string "ai". And you're testing the regular expression against the array. I think what you meant to write is:
if(RegExp(a[i]).test(s)) alert(1);
You would probably be better off just using indexOf in this case. It'll be faster and you won't need to escape any characters.
var a = ["abc","def","ghi"],
s = "jskljfdkljflkjk abc jskfdjklsj";
for(var i = 0, l = a.length; i < l; i++)
if(s.indexOf(a[i])+1) alert('string s contains a value from array a');
function doesStringContainElementFromArray(str, arr)
{
for ( var i=0; i<arr.length; i++)
{
if ( str.indexOf(arr[i]) != -1 )
return true;
}
return false;
}
Just use the "RegExp" function/constructor (if you really need regexps)
if (RegExp(a[i]).test(a)) {
alert(1);
}
if you don't, just use .indexOf
if (s.indexOf(a[i]) != -1) {
alert("a[i]="+a[i]+" is matched in " + s);
}
You can use search method of JavaScript
var a = ["abc","def","ghi"];
var s = "jskljfdkljflkjk abc jskfdjklsj";
for(var i=0;i<a.length;i++){
if(s.search( a[i] ) != -1)
{
alert("found");
}
}

Generate Array Javascript

I want to generate an array in jQuery/JS, which contains "code"+[0-9] or [a-z].
So it will look like that.
code0, code1 ..., codeA, codeB
The only working way now is to write them manually and I am sure this is a dumb way and there is a way to generate this automatically.
If you give an answer with a reference to some article where I can learn how to do similar stuff, I would be grateful.
Thank you.
For a-z using the ASCII table and the JavaScript fromCharCode() function:
var a = [];
for(var i=97; i<=122; i++)
{
a.push("code" + String.fromCharCode(i));
}
For 0-9:
var a = [];
for(var i=0; i<=9; i++)
{
a.push("code" + i);
}
I'm using the unicode hexcode to loop through the whole symbols from 0-z:
var arr = [];
for (var i = 0x30; i < 0x7b;i++){
// skip non word characters
// without regex, faster, but not as elegant:
// if(i==0x3a){i=0x41}
// if(i==0x5b){i=0x61}
char = String.fromCharCode(i);
while(!/\w/.test(char)){char = String.fromCharCode(i++)};
// generate your code
var res = "code"+char;
// use your result
arr.push(res);
}
console.log(arr);
Here goes your example.
Docs:
Unicode Table
for loop
fromCharCode
JS Array and it's methods
you can generate array in javascript by using following code.
var arr = [];
for (var i = 0; i < 5; i++) {
arr.push("code"+ i);
}
please refer following links.
https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/Array
http://www.scriptingmaster.com/javascript/JavaScript-arrays.asp
a = [];
for(i = 48; i < 91; i++) {
if (i==58) i = 65
a.push("code" + String.fromCharCode(i));
}
alert(a.join(',')) // or cou can print to console of browser: console.log(a);

Retrieve substring between two characters

I have string like this
var str = "#it
itA
itB
_
#et
etA
etB
_
etC
etD"
How can I retrieve elements between # and _. As of now I am splitting the text with new line but unable to workout this. Please help me on this. Please use this fiddle http://jsfiddle.net/h728C/2/
IF you simply want the FIRST string BETWEEN you can use:
var mys= str.substring(str.indexOf('#')+1,str.indexOf("_"));
this returns: "it itA itB"
I've posted some solution in fidde. It uses the Regex
var str = $('#a').text();
var pattern = /#([\s\S]*?)(?=_)/g;
var result = str.match(pattern);
for (var i = 0; i < result.length; i++) {
if (result[i].length > 1) {
result[i] = result[i].substring(1, result[i].length);
}
alert(result[i]);
}
Strip the end and beginning.
Edit
I've updated the fiddle and the code. Now it strips the beginning # and ending _.
You can use either. Whichever is convenient.
​
​
I don't really get why but this works:
var str = $('#a').text();
var results = [];
$.each(str.split("_"), function(){
var a = this.toString().split("#");
if(a.length===2) results.push(a[1]);
});
console.log(results);​
You can use this kind of regex:
str.replace(/\s/g, "").match(/#(.*?)_/g, "$1");
See this fiddle.
one line solution to get the array
var arrStr = str.split(/[#_]/);
I would not recommend using regex here as it can be done more efficiently through other methods.
function extractString(template, initChar, finalChar) {
let i = 0;
let data = [];
do {
if (template[i] == initChar) {
for (let j = i + 1; j < template.length; j++) {
if (template[j] == finalChar) {
data[data.length] = template.slice(i + 1, j);
i = j + 1;
break;
}
}
}
}
while (++i < template.length);
console.log(data)
return data;
}
extractString("#adj#, #brown# fox jumps over the lazy #dog#.","#","#");

Categories

Resources