Splitting string array of one value fails - javascript

I have this:
var ID= "12,32,23,78";
var i = ID.split(',');
If I do this then it works fine, but when it is only one value like 12, then it gives me 0. How I can solve this issue? If I need to check for only one value, how do you do that?

If the variable "ID" is the number 12, then of course it doesn't work — the .split() method is a method for strings, not numbers. Try this:
var ID = /* whatever */;
var i = (ID + '').split(',');

var i;
if (ID.indexOf(",") != -1)
i = ID.split(',');
else
i = ID;

Exactly like what you posted except you check for the presence of the seperator with JavaScripts .indexOf() string method.

var ID= "12,32,23,78";
var i = ID.split(',');
will return [12,32,23,78]
var ID= "12";
var i = ID.split(',');
will return [12] -- this is also an array
however you may do this
var ID= "12";
var i = ID.split(',') || ID;

String.prototype.mySplit = function(sep) {
return (this.indexOf(sep) != -1) ? this.split(sep) : [this];
};
Example:
//var ID= '12,32,23,78';
var ID= '12';
//Update
if (typeof(ID)=='number') ID += '';
var i = ID.mySplit(',');
alert(i[0]);

Related

Get split number and string from string

I have an array of string like below:
var array =[];
array.push("Complex12");
array.push("NumberCar1");
array.push("Protect5");
I want to split the string and number of each item.
var Id = parseInt(array[0].match(/\d/g));
var type = array[0].replace(/\d+/g, '');
But I only get Id = 1(I want 12) and type = "Complex", where am I wrong?
thanks
I think you just missed + in first regexp
var Id = parseInt(array[0].match(/\d+/g));
Do it in one pattern with capture groups:
var mystr = "Complex12";
if (m = mystr.match(/^([a-z]+)([0-9]+)$/i)) {
var type = m[1];
var id = m[2];
}

Javascript pull data from string?

I have a long URL that contains some data that I need to pull. I am able to get the end of the URL by doing this:
var data = window.location.hash;
When I do alert(data); I receive a long string like this:
#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600
note in the example the access token is not valid, just random numbers I input for example purpose
Now that I have that long string stored in a variable, how can I parse out just the access token value, so everything in between the first '=' and '&. So this is what I need out of the string:
0u2389ruq892hqjru3h289r3u892ru3892r32235423
I was reading up on php explode, and others java script specific stuff like strip but couldn't get them to function as needed. Thanks guys.
DEMO (look in your debug console)
You will want to split the string by the token '&' first to get your key/value pairs:
var kvpairs = document.location.hash.substring(1).split('&');
Then, you will want to split each kvpair into a key and a value:
for (var i = 0; i < kvpairs.length; i++) {
var kvpair = kvpairs[i].split('=');
var k = kvpair[0];
var v = kvpair[1];
if (k != 'access_token')
continue;
console.log(v); //Here's your access token.
}
Here is a version wrapped into a function that you can use easily:
function getParam(hash, key) {
var kvpairs = hash.substring(1).split('&');
for (var i = 0; i < kvpairs.length; i++) {
var kvpair = kvpairs[i].split('=');
var k = kvpair[0];
var v = kvpair[1];
if (k != key)
continue;
return v;
}
return null;
}
Usage:
getParam(document.location.hash, 'access_token');
data.split("&")[0].split("=")[1]
var str = "#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600";
var requiredValue = str.split('&')[0].split('=')[1];
I'd use regex in case value=key pair changes position
var data = "#token_type=Bearer&access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&expires_in=3600";
RegExp("access_token=([A-Za-z0-9]*)&").exec(data)[1];
output
"0u2389ruq892hqjru3h289r3u892ru3892r32235423"
Looks like I'm a bit late on this. Here's my attempt at a version that parses URL parameters into a map and gets any param by name.
var str = "#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600";
function urlToMap(url){
var startIndex = Math.max(url.lastIndexOf("#"), url.lastIndexOf("?"));
url = url.substr(startIndex+1);
var result = {};
url.split("&").forEach(function(pair){
var x = pair.split("=");
result[x[0]]=x[1];
});
return result;
}
function getParam(url, name){
return urlToMap(url)[name];
}
console.log(getParam(str, "access_token"));
To answer to your question directly (what's between this and that), you would need to use indexOf and substring functions.
Here's a little piece of code for you.
function whatsBetween (_strToSearch, _leftText, _rightText) {
var leftPos = _strToSearch.indexOf(_leftText) + _leftText.length;
var rightPos = _strToSearch.indexOf(_rightText, leftPos);
if (leftPos >= 0 && leftPos < rightPos)
return _strToSearch.substring(leftPos, rightPos);
return "";
}
Usage:
alert(whatsBetween, data,"=","#");
That said, I'd rather go with a function like crush's...
try this
var data = window.location.hash;
var d1 = Array();
d1 = data.split("&")
var myFilteredData = Array();
for( var i=0;i<d1.length;i++ )
{
var d2 = d1[i].split("=");
myFilteredData.push(d2[1]); //Taking String after '='
}
I hope it helps you.

Find text between two characters and for each, do something

I have a file full with text in the following format:
(ignoring the fact that it is CSS) I need to get the string between the two | characters and each time, do something:
<div id="unused">
|#main|
#header|
.bananas|
#nav|
etc
</div>
The code I have is this:
var test_str = $('#unused').text();
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
//I want to do something with each string here
This just gets the first string. How can I add logic in there to do something for each string?
You can use split method to get array of strings between |
Live Demo
arr = $('#unused').text().split('|');
You can split like
var my_splitted_var = $('#unused').text().split('|');
One way;
$.each($("#unused").text().split("|"), function(ix, val) {
val = $.trim(val); //remove \r|\n
if (val !== "")
alert(val);
});
One way :
var test_str = $('#unused').text();
while(!test_str.indexOf('|'))
{
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
test_str = test_str.slice(end_pos,test_str.length);
}
RegExp-Version:
LIVE DEMO (jsfiddle.net)
var trimmedHtml = $("#unused").html().replace(/\s/g, '');
var result = new Array();
var regExp = /\|(.+?)(?=\|)/g;
var match = regExp.exec(trimmedHtml);
result.push(match[1]);
while (match != null) {
match = regExp.exec(trimmedHtml);
if (match != null) result.push(match[1]);
}
alert(result);
So you only get the elements BETWEEN the pipes (|).
In my example I pushed every matching result to an array. You can now iterate over it to get your result.

remove all empty values from url

I want to remove all empty values from an url:
var s="value1=a&value2=&value3=b&value4=c&value5=";
s = s.replace(...???...);
alert(s);
Expected output:
value1=a&value3=b&value4=c
I only need the query part of the URL to be taken into account.
Something like this:
s = s.replace(/[^=&]+=(&|$)/g,"").replace(/&$/,"");
That is, remove groups of one or more non-equals/non-ampersand characters that are followed by an equals sign and ampersand or end of string. Then remove any leftover trailing ampersand.
Demo: http://jsfiddle.net/pKHzr/
s = s.replace(/[^?=&]+=(&|$)/g,"").replace(/&$/,"");
Added a '?' to nnnnnn's answer to fix the issue where the first parameter is empty in a full URL.
This should do the trick:
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmp = s.split('&')
var newS = '';
for(var i in a) {
var t = a[i];
if(t[t.length - 1] !== '=') {
newS += t + '&';
}
}
if(newS[newS.length - 1] === '&') {
newS = newS.substr(0, newS.length - 1);
}
console.log(newS);
I don't find any solution to do that with one Regex expression.
But you could loop through your string and construct a new result string : http://jsfiddle.net/UQTY2/3/
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmpArray = s.split('&');
var final = '';
for(var i=0 ; i<tmpArray.length ; i++)
if(tmpArray[i].split('=')[1] != '')
final += tmpArray[i] + '&';
final = final.substr(0,final.length-1)
alert(final)
Where do you take all the values?
I suggest using an array:
function getValues(str){
var values = [];
var s = str.split('&');
for(var val in s){//source is a
var split = val.split('=');
if(split [1] != '' && split [1] != null){
values.push(val);
}
}
return values.join('&');
}

How to filter comma separated integer values in javascript

I have a varaiable in javascript like the following
var element = parent.document.getElementById('productCollectionField');
var values = element.value;
and an input field like
<input type="hidden" value="1,2,3,4" id ="productCollectionField" />
so var element contains 1,2,3,4
Now I have value 5 and i want to check it in values .? How can i do that...? These numbers can be anything.
var myResults = values.split(",")
You will then have an array you can parse
The simplest solution is to use the following function, which returns true of false whether the number is in the value string or not.
var value = '1,2,3,4';
function checkNumber(number, values) {
var numberExists = false;
var strArray = values.split(",")
for (var i = 0; i < strArray.length; i++)
{
// You could use if (strArray[i] == number), but using === is advised
// since it's more specific about the type
if ( parseInt(strArray[i]) === number)
numberExists = true;
}
return numberExists;
}
// returns false
checkNumber(5, value);
// returns true
checkNumber(2, value);
Is jQuery available to you? If yes, you can do it like this:
First, what JMax said:
var myResults = values.split(",")
Define the string that will be the output after the merge:
var newString = '';
Then,
if ( jQuery.inArray( 5, myResults ) == -1 ) {
myResults.push( 5 );
newString = myResults.join(',');
}
Cheers,

Categories