How to substring the string using jQuery - javascript

I am using jQuery
I have got below in my string
str = "Michael,Singh,34534DFSD3453DS"
Now I want my result in three variables.
str1 = "Michael"
str2 = "Singh"
str3 = "34534DFSD3453DS"
Please suggest!
Thanks

var strs = str.split(',') is your best bit. This will create an array for you so
strs[0] = "Michael"
strs[1] = "Singh"
strs[2] = "34534DFSD3453DS"
However, it is possible to get exactly what you want by adding new items to the window object. For this I use the $.each method of jQuery. It's not necessary (you can just use a for) but I just think it's pretty :). I don't recommend it, but it does show how you can create new variables 'on the fly'.
var str = "Michael,Singh,34534DFSD3453DS";
$.each(str.split(','), function(i,item){
window['str' + (i+1)] = item;
});
console.log(str1); //Michael
console.log(str2); //Singh
console.log(str3); //34534DFSD3453DS
Example: http://jsfiddle.net/jonathon/bsnak/

No jQuery needed, just javascript:
str.split(',')
Or, to get your 3 variables:
var arr = str.split(','),
str1 = arr[0],
str2 = arr[1],
str3 = arr[2];

You don't need jQuery. Javascript does that built-in via the split function.
var strarr = str.split(',');
var str1 = strarr[0];
var str2 = strarr[1];
var str3 = strarr[2];

Just use split() and store each word inside an array
var str = "Michael,Singh,34534DFSD3453DS"
var myArray = str.split(",");
// you can then manually output them using their index
alert(myarray[0]);
alert(myarray[1]);
alert(myarray[2]);
//or you can loop through them
for(var i=0; i<myArray.length; i++) {
alert(myArray[i]);
}

It's not only that JQuery is not needed but that JQuery is not meant to do such tasks. JQuery is for HTML manipulation, animation, event handling and Ajax.

Related

How to remove a part of all strings in an array in javascript?

I want split array value .
for example
gUser[1] = CAR.BENZ.CCLASS.1962
gUser[2] = CAR.PORSCHE.911.2001
I want get string only BENZ.CLASS.1962 and PORSCHE.911.2001
How to split array value on java script?
#update.
not always CAR string.
so, not use substring.
You can use map to access each string in array then use replace. Use a regex to match string before '.' and replace only the first match, like this:
var gUser = ['CAR.BENZ.CCLASS.1962', 'CAR.PORSCHE.911.2001'];
var gUserModified = gUser.map(function(v){
return v.replace(/[^\.]+\./, '');
});
console.log(gUserModified);
Split it with dot then slice it and join it with dot
var gUser =[];
gUser[1] = "CAR.BENZ.CCLASS.1962";
gUser[2] = "CAR.PORSCHE.911.2001";
console.log(gUser[1].split('.').slice(1).join('.'));
console.log(gUser[2].split('.').slice(1).join('.'));
From your question, it's not clear if the array is a string array
If it is a string array you can do:
ES6+: gUser.map((user)=>{return user.split("CAR.")[1]})
ES5: gUser.map(function(user){return user.split("CAR.")[1]});
The below code is not tested but should probably work, with maybe minor tweaks
var splitStr = ''
var correctCarArr = []
for(let i = 0; i < gUser.length; i++){
splitStr = gUser[i].split('.')
let temp = ''
for(let j = 1; j < splitStr.length; j++){
temp += splitStr[j]
}
correctCarArr.push(temp)
}
var gUser = [];
gUser[1] = "CAR.BENZ.CCLASS.1962";
var gu1 = gUser[1].split(".");
gu1.shift();
console.log(gu1.join("."));
So here is the way without using any regex by only using string and array methods.
const gUser = ['CAR.BENZ.CCLASS.1962', 'CAR.PORSCHE.911.2001', 'XYZAB.PORSCHE.YSA.2021']
for (let i = 0; i < gUser.length; i++) {
console.log('Required String: ', gUser[i].split('.').slice(1).join('.'));
}
What we do is, we split the string into parts where . is encountered.
gUser[0].split('.') returns ['CAR', 'BENZ', 'CCLASS', '1962']
Later when slice(1) is called, the zeroth element of array is chopped off and will return ['BENZ', 'CCLASS', '1962']
And finally using join('.'), we merge the array elements to a single string with a . between each element, which returns BENZ.CCLASS.1962
Hope this helps! :)
Its easier split then shift the array to remove the first item like this:
gUser = ["CAR.BENZ.CCLASS.1962"];
var benz = gUser[0].split(".");
benz.shift();
alert(benz.join('.'));
There are other options from shift like slice(1) but In terms of performance, shift is apparently faster https://jsperf.com/shift-pop-vs-slice/4
Something Like This
`for(let index = 0; index < gUser.length; index++) {
console.log(gUser[index].split('.').splice(0, 1).join('.'));
}`
I haven't tested it. Please check and let me know

Splitting a string between two reoccurring characters

I have dynamic values in a variables, each separated with [ and ] e.g.
var data="[Continuing] [Returning] "; or
var data="[ACCT_BBA] "; or
var data="[12001] [12009] [21077] [13880] ";
var data="[13880] ";
Is there a way to use the split function to extract the values between the [ and the ] from above?
var arr= data.split("<what goes here?>");
e.g. on the last example to retrieve: 12001, 12009, 21077, 13880
data.slice(1, -2).split("] [")
should do the job, or if your start and end are uncertain maybe
data.replace(/^\s*\[|\]\s*$/g, "").split("] [")
Alternatively, if you need something more complex, the choice is usually .match with a global regex, or building your own parser if you need to handle arbitrarily nested structures.
Use
data.split('] [').map(function (item) { return item.replace("]", "").replace("[", "")})
like this:
//var data="[Continuing] [Returning]";
// var data="[ACCT_BBA]";
var data="[12001] [12009] [21077] [13880]";
var res = data.split('] [').map(function (item) { return item.replace("]", "").replace("[", "")})
console.log(res)
What about data.match(/\[(\w+)\]/g).map(e => e.slice(1, -1))
And you can replace \w with the scope of character, like [a-zA-Z0-9_]
Yes if you do:
var data="[12001] [12009] [21077] [13880]";
var arr = data.split(" ");
for(let i = 0; i < arr.length; i++){
arr[i] = arr[i].replace('[','');
arr[i] = arr[i].replace(']','');
}
console.log(arr);
just an example, very basic one.

JS: Check Query String for GET variables that are not in an array?

Let's say I have an address of:
www.example.com/index.php?a=1&b=2&c=3
I want to enter that into an input field like this (value would obviously initially be blank):
<input id="my-input-field" value="www.example.com/index.php?a=1&b=2&c=3">
Then I want JS to parse everything after the ?, take all of the queries ("a", "b", "c") and see if they exist in an array().
Then I want to display a message stating that some of the items in the given URL were missing - but that's the easy part.
The part that I'm having trouble figuring out is: how to break down the URL and only find the first part of each query?
I understand how to strip everything before the question mark (including the question mark):
var str = "www.example.com/index.php?a=1&b=2&c=3";
str = str.substring(str.indexOf("?") + 1);
alert(str);
Fiddle: http://jsfiddle.net/xx3fwhvv/
This returns: a=1&b=2&c=3
The next step could be to split the string up per each &?
var str = "a=1&b=2&c=3";
str = str.split("&");
alert(str);
Fiddle: http://jsfiddle.net/3Lo24byo/
This returns: a=1,b=2,c=3
We can then remove everything after the ='s sign like this:
var str = 'a=1';
str = str.substring(0, str.indexOf('='));
alert(str);
Fiddle: http://jsfiddle.net/vfzvu5mh/
This results in: a
The thing now is how do I loop through the array and do this for each item? That would be the step I need to take.
Then I need to have an array like:
var myArray = array('a','c','d');
In the above array, cross checking the array that we created above to see if any of the values match up should return b as not matching up, as it's not in myArray.
This is where I'm stuck. Any help is appreciated. I'm not very good with JS but I've been working at this trying to figure it out.
All together so far, the code would look something like this:
var str = "www.example.com/index.php?a=1&b=2&c=3";
newStr = str.substring(str.indexOf("?") + 1);
strArray = newStr.split("&");
i = 1;
for {
newStrArray = strArray[i].substring(0, strArray[i].indexOf('='));
i++;
}
The above doesn't work for me, but something like that any way.
EDIT (I'll be actively editing this part until the question is answered):
var str = "www.example.com/index.php?a=1&b=2&c=3";
var newStr = str.substring(str.indexOf("?") + 1);
var myStringArray = newStr.split("&");
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
myStringArray = myStringArray[i].substring(0, myStringArray[i].indexOf('='));
alert(myStringArray[i]);
}
Current Fiddle: https://jsfiddle.net/03ho0nbz/
First off, you're overwriting your array with the result of a substring:
myStringArray = myStringArray[i].substring(0, myStringArray[i].indexOf('='));
myStringArray receives the results of the substring, turning it into a string.
To compare myArray with otherArray and see if an element not exists in myArray you can use the indexOf() function:
var myArray = ['a', 'c', 'd'];
var otherArray = ['a', 'b', 'c'];
for(var i=0;i<otherArray.length;i++) {
if(myArray.indexOf(otherArray[i]) === -1) {
console.log('myArray does not have', otherArray[i]); // myArray does not have b
}
}
Going by your example this would create a loop looking something like:
var str = "www.example.com/index.php?a=1&b=2&c=3";
var newStr = str.substring(str.indexOf("?") + 1);
var myStringArray = newStr.split("&");
var myArray = ['a', 'c', 'd'];
for (var i = 0; i < myStringArray.length; i++) {
var eqIndex = myStringArray[i].indexOf('=');
if(eqIndex !== -1) {
var key = myStringArray[i].substring(0, eqIndex);
if(myArray.indexOf(key) === -1) {
alert(key, "not in myArray!");
}
}
}
Note that this way of writing JS is fine for learning practices, but if you intend to use JS in a professional setting, please read up on some JS good practices.
What i would do is to fiddle around with JS like you're doing, try and see if you can buy some JS good practices books and also look at how popular frameworks solve things. For professional purpose it's almost always a good idea to use a framework that's well maintained and supported. For example if you would use underscore in this case you could do something like:
var paramKeys = _.chain("a=1&b=2&c=3".split('&')).map(function(params) {
var p = params.split('=');
return p[0];
}).value();
_.difference(paramKeys, ['a', 'c', 'd']) // "b"
#mattroberts33 I am unable to understand why you are checking first parameter in the url, is there anything deference from www.example.com/index.php?a=1&b=2&c=3 to www.example.com/index.php?b=2&a=1&c=3. I would encourage read parameters based on the keys instead of index. In any url query parameters might jumbled.
Below method will return parameter by passing key and url to the method:
var getParameterByName = function (name, url) {
name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
if (url) {
var results = regex.exec(url);
} else {
var results = regex.exec(location.search);
}
return results == null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));};
If you still wants to get based on index we can modify above method, But that is not encouraging.

How to get string in regular expression with space

This is my input as string
'controls: ["aa.bb.cc","dd.ee.ff"],elements: []'
I want to get the result of the data in the controls meaning :
"aa.bb.cc","dd.ee.ff"
I tried pattern
/.*(controls:.*).*/
but I didn't get all the result
I think my problem is becuase the new line
You can do it with regEx
var c = 'controls: ["aa.bb.cc", "dd.ee.ff"], elements: []';
var match = c.match(/("[a-z.]+")/g);
// or c.match(/([a-z][a-z][.][a-z][a-z][.][a-z][a-z])/);
// to strictly match letters . letters . letters
// or for a shorter match: c.match(/(\w+[.]\w+[.]\w+)/);
console.log(match); // an array of your values
EDIT:
if you only want to get the values in controls and not element, you can get the controls values out with the regEx /controls: ([\["a-z., \]]+,)/g
You could simply parse your input as a JSON object then loop throught the controls array:
var input='controls: ["aa.bb.cc", "dd.ee.ff"],
elements: []';
json = JSON.parse(input);
var controls=json.controls;
//then loop throught the controls values
for(var i=0;i<controls.length;i++){
console.log(controls[i]);
}
I think that should do it.
This might look like a very crude solution, but it works.
This expression will give you aa.bb.cc :
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[1]
and this will give the next element i.e. dd.ee.ff
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[2]
In general,
var str = "controls: [\"aa.bb.cc\",\"dd.ee.ff\"],elements: []";
var resLength = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/).length;
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/);
for (var i=1; i<resLength; i++) {
console.log(res[i]);
}

Parse values out of paramaterized strings in javascript

Say I have a string, such as:
var map = "/directory/:id/thumbnails/:size";
And I want to use that to map against another string (essentially, the same thing that Rails uses to define Routes), such as:
var str = "/directory/10/thumbnails/large";
I would like to "compare" the two strings, and return a Key-Value Pair or JSON Object that represents the parts of str that map to map, which in my example above, would look like:
obj = {
'id' : '10',
'size' : 'large'
}
Would this be a good fit for JavaScript Regex? Can anyone help me?
I found it easier to just write the code for this than to explain :)
var map = "/directory/:id/thumbnails/:size";
var str = "/directory/10/thumbnails/large";
var obj = {};
var mapArr = map.split('/');
var strArr = str.split('/');
if (mapArr.length != strArr.length) return false;
for (var i = 0; i < mapArr.length; i++)
{
var m = mapArr[i];
var s = strArr[i];
if (m.indexOf(":") != 0) continue;
m = m.substring(1);
obj[m] = s;
document.write(m + " = ");
document.write(obj[m]);
document.write("<br/>");
}
You can also see it in action here => http://jsfiddle.net/5qFkb/
Do ask if you have any questions, but the code should be self-explanatory. Also be aware that there is no usual null checking and stuff I'd usually put in - this is just meant as a quick and dirty proof of concept.
Oh and in case it wasn't clear from my answer; no, I wouldn't use regex, because then I'd have two problems instead of one.

Categories

Resources