Select 2 characters after a particular substring in javascript - javascript

We have a string ,
var str = "Name=XYZ;State=TX;Phone=9422323233";
Here in the above string we need to fetch only the State value i.e TX. That is 2 characters after the substring State=
Can anyone help me implement it in javascript.

.split() the string into array and then find the index of the array element having State string. Using that index get to that element and again .split() it and get the result. Try this way,
var str = "Name=XYZ;State=TX;Phone=9422323233";
var strArr = str.split(';');
var index = 0;
for(var i = 0; i < strArr.length; i++){
if(strArr[i].match("State")){
index = i;
}
}
console.log(strArr[index].split('=')[1]);
jsFiddle

I guess the easiest way out is by slicing and splitting
var str = "Name=XYZ;State=TX;Phone=9422323233";
var findme = str.split(';')[1];
var last2 = findme.slice(-2);
alert(last2);
Need more help? Let me know

indexOf returns the position of the string in the other string.
Using this index you can find the next two characters
javascript something like
var n = str.indexOf("State=");
then use slice method
like
var res = str.slice(n,n+2);
another method is :
use split function
var newstring=str.split("State=");
then
var result=newstring.substr(0, 2);

Check this:
var str1 = "Name=XYZ;State=TX;Phone=9422323233";
var n = str1.search("State");
n=n+6;
var res = str1.substr(n, 2);
The result is in the variable res, no matter where State is in the original string.

There are any number of ways to get what you're after:
var str = "Name=XYZ;State=TX;Phone=9422323233"
Using match:
var match = str.match(/State=.{2}/);
var state = match? match[0].substring(6) : '';
console.log(state);
Using replace:
var state = str.replace(/^.*State=/,'').substring(0,2);
console.log(state);
Using split:
console.log(str.split('State=')[1].substring(0,2));
There are many other ways, including constructing an object that has name/value pairs:
var obj = {};
var b = str.split(';');
var c;
for (var i=b.length; i; ) {
c = b[--i].split('=');
obj[c[0]] = c[1];
}
console.log(obj.State);
Take your pick.

Related

Build key/value Object from slash-separated URL

Given a slash separated URL like http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3 how could I build a key/value Object with the dynamic parameters (param1/value, param2/value2...) of this URL?
Valid parameters always have this slash separated paramand value format and some/fixed/path would be a substring manually provided.
I tried to split the full URL (or whatever it could be) by the fixed substring and I managed to slice the dynamic params out of it as I wanted but I couldn't create the key/value Object as I needed:
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var result = {};
url.split( uri ).forEach(function(x){
var arr = x.split('/');
arr[1] && (result[arr[0]] = arr[1]);
});
console.log( result );
But this piece of code only brings me the first pair instead of all of them and it requires the uri to obligatorily have a trailing slash. If the substring doesn't have it or has one to the left it acts all weird with a blank key and the first key as value o.O
I know it's simple, but I just can't do it. I tried to search but this must have a very specific way to refer to because I couldn't find by my own.
One last thing, if you don't mind explain instead of just give me the fish, I'd appreciate, so there won't have a next time... hopefully
You were only taking the second part after some/fixed/path/. You need to split this second part and iterates over the array. On each even index, I create a new property in the object with the name of the previous element
x is the current element
i is the current index
a is the array containing each element after splitting with /
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var result = {};
var paramsToSplit = url.split(uri)[1];
paramsToSplit.split('/').forEach((x,i,a)=>{
if(i%2)
result[a[i-1]] = x;
});
console.log( result );
Try this:
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var url = url.substring(url.indexOf(uri) + uri.length)
var options = url.split('/');
var results = [];
for(var i=0;i<options.length; i+=2){
results.push({[options[i]]:options[i+1]})
}
Are you looking for somethig like that?
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var params = [];
var values = [];
var results = {};
url.split( uri )[1].split('/').forEach(function(e,i) {
if(i%2==0){
params.push(e)
} else {
values.push(e);
}
})
console.log( params, values );
params.forEach(function(e,i) {
results[e] = values[i];
});
console.log( results );
You may do as follows;
var text = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
result = text.split("/")
.slice(6)
.reduce((r,c,i,a) => i&1 ? Object.assign(r,{[a[i-1]]: c}) : r, {});
console.log(result);
You are quite close, you basically need to make another for loop for your produced arr and step every 2 values. Like so...
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var result = {};
url.split( uri ).forEach(function(x){
var arr = x.split('/');
var step;
for (step = 0; step <= arr.length; step += 2) {
arr[step + 1] && (result[arr[step]] = arr[step + 1]);
}
});
console.log( result );

Get max value of similar items in array with Javascript

I have an array like this:
["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"]
and I want to get a final array that will group similar values that changes from each other only by the last numbers of the string ("13rq8", "13rq6", "13rq4", "13rq2", "13rq12", "13rq10"), and return only the biggest values like the example below:
["13dl", "12dl", "13rq12"]
Can you help me please resolve this in Javascript?
Thank You!
Use an object (ex. tagNum) to keep track of the largest value of each prefix, and use regular expression to extract the prefix and trailing value:
var l = ["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"];
var tagNum = {};
l.forEach(function(x) {
var m = x.match(/^(.*?)(\d*)$/);
var tag = m[1];
var num = parseInt("0" + m[2]);
if (tagNum[tag] === undefined || tagNum[tag] < num) tagNum[tag] = num;
});
var l2 = [];
for (var tag in tagNum) {
var num = tagNum[tag];
if (num) l2.push(tag + num);
else l2.push(tag);
}
console.log(l2);

How to split two dimensional array in JavaScript?

I have string like below:
"test[2][1]"
"test[2][2]"
etc
Now, I want to split this string to like this:
split[0] = "test"
split[1] = 2
split[2] = 1
split[0] = "test"
split[1] = 2
split[2] = 2
I tried split in javascript but no success.How can it be possible?
CODE:
string.split('][');
Thanks.
Try this:
.replace(/]/g, '') gets rid of the right square bracket.
.split('[') splits the remaining "test[2[1" into its components.
var str1 = "test[2][1]";
var str2 = "test[2][2]";
var split = str1.replace(/]/g, '').split('[');
var split2 = str2.replace(/]/g, '').split('[');
alert(split);
alert(split2);
you can try :
string.split(/\]?\[|\]\[?/)
function splitter (string) {
var arr = string.split('['),
result = [];
arr.forEach(function (item) {
item = item.replace(/]$/, '');
result.push(item);
})
return result;
}
console.log(splitter("test[2][1]"));
As long as this format is used you can do
var text = "test[1][2]";
var split = text.match(/\w+/g);
But you will run into problems if the three parts contain something else than letters and numbers.
You can split with the [ character and then remove last character from all the elements except the first.
var str = "test[2][2]";
var res = str.split("[");
for(var i=1, len=res.length; i < len; i++) res[i]=res[i].slice(0,-1);
alert(res);

Splitting string on first equals sign in javascript

I am trying to use Javascript to split some data out of a url The url looks along the lines of....
var1=green&var2=yellow&newUrl=[url.php?id=2]
I am managing to split the url by the '&' signs to give me one array of three items. I am then trying to split this array by the first '=' sign to give me a list of fields and variables. Its working fine until it hits the second = sign within the newUrl field. Any ideas of how I can split this string at the first '=' sign.
my code so far is...
var href = $(this).attr("href");
var vars = href.split("&");
for(i=0; i < vars.length; ++i){
var str = vars[i].split("=");
alert(str[0] +':' +str[1]);
}
}
my results are
var1:green var2:yellow var3:[url.php?id
Any ideas?
**Edit to show my final code based on Wand Maker's solution **
var vars = href.split("&");
for(i=0; i < vars.length; ++i){
index = vars[i].indexOf("=")
var str = [ vars[i].substring(0, index), vars[i].substring(index)]
alert(str[0] +':' +str[1].substring(1);
}
Try something like below for splitting around =
index = vars[i].indexOf("=")
var str = [ vars[i].substring(0, index), vars[i].substring(index)]
You could use join() for the third element in the array as below:
var lst = href.split("&");
var var1 = href[0].split("=")[1];
var var2 = href[1].split("=")[1];
var var3 = href[2].split("=").slice(1,2).join("");
function splitFirstInstance(str,item){
var res = [];
var found = true;
res.push("");
for (var i = 0; i < str.length;i++){
if (str[i] === item && found === true){
res.push("");
found = false;
} else {
res[res.length-1] += str[i];
}
}
return res;
}
splitstr("I Want to Split First a","a"); // ["I W","nt to Split First a"]

Split a variable in js or jquery

Hi I have some vars like this:
var a = Base-Shirt_Stripe.jpg
var b = Closed-Flatknit-Collar_Stripe.png
How do i create two new vars like:
var c = Base-Shirt
var d = Stripe
or
var e = Closed-Flatknit-Collar
var f = Stripe
basically split at the _ remove the _ and remove the extension.
//for example, we take a
var a = 'Base-Shirt_Stripe.jpg';
//then we take the part of a before the dot
//and split between `_`
//split returns an array
var split = a.substring(0,a.indexOf('.'))
.split('_');
//split is an array, so we use indices to indicate which
console.log(split[0]); //Base-Shirt
console.log(split[1]); //Stripe
Sample here. You can do the same for your b
may be you could do like
var a = "Base-Shirt_Stripe.jpg"
var k = a.replace(/(\.\w*)$/g, "").split("_");
alert(k[0]);
alert(k[1]);
here is the fiddle
You need to make them strings to start with, then use String.split() to split the string into an array of the different parts.
jsFiddle
var a = "Base-Shirt_Stripe.jpg"
var b = "Closed-Flatknit-Collar_Stripe.png"
var aSplit = a.substr(0, a.lastIndexOf('.')).split('_');
var c = aSplit[0];
var d = aSplit[1];
var bSplit = b.substr(0, b.lastIndexOf('.')).split('_');
e = bSplit[0];
f = bSplit[1];
You could also take the removal of the extension out into its own function using String.lastIndexOf() and String.substr().
function removeExtension(file) {
return file.substr(0, file.lastIndexOf('.'));
}
//Javascript Split can divide it into parts. Javascript Split return type is array.'
//e g.
var a = Base-Shirt_Stripe.jpg
var parts = a.split('_');
console.log(parts[0]);
//output
" Base-Shirt "
//parts[0] contain base-shirt and parts[1] contain Stripe.jpg.

Categories

Resources