Splitting string on first equals sign in javascript - 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"]

Related

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);

Select 2 characters after a particular substring in 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.

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)

how to search data from array if matches any of the character of any value in array using Javascript

I am using following code to get the index value of the particular but now it will show a but i want that it may show all the index values having character a
Like we do searching
var con = document.getElementById('data');
var char = 'a';
var str = '';
var ad = ['abc', 'a', 'call', 'all', 'ded', 'ee', 'aee'];
var count = ad.filter(function (v) {
return v == char;
}).length;
for (var i = 0; i < count; i++)
str += char;
alert(str);
con.innerHTML = str;
here is the jsfiddel link
http://jsfiddle.net/Pescf/7/
Try like below, it will help you...
Updated Fiddle : http://jsfiddle.net/Pescf/24/
var con = document.getElementById('data');
var char = 'a';
var str = '';
var ad = ['ali', 'bbc', 'call', 'a', 'd', 'eaa', 'ab'];
var len = ad.length;
for (var j=0; j<len; j++) {
var str = ad[j];
var n=str.indexOf(char);
if (n==0)
con.innerHTML += str + "<br>";
}
its output is like below...
ali
a
ab
Given the new requirement that the character be at the beginning of the string:
http://jsfiddle.net/jeffshaver/Pescf/26/
If you need to keep track of the current array element, the best way would probably to just iterate over the entire array and not just the number of elements in the array that have the character.
Inside the for loop, just check for whether the current item has the character in it: http://jsfiddle.net/jeffshaver/Pescf/13/
I think I understand... Try replacing return v == char; with return v.indexOf(char) !== -1. Currently count only equals 1, so it won't do what you want. Changing this will cause count to equal 5, getting you the result you desire (I think).
The reason that return v == char doesn't work is because you are testing whether or not the full string equals a single character, which only exists one time.
Instead, indexOf will check to see if a string contains a character.
Try like this
var con = document.getElementById('data');
var char = 'a';
var str = '';
var ad = ['ali', 'bbc', 'call', 'a', 'd', 'eaa', 'ab'];
for (var i = 0; i < ad.length; i++)
if (ad[i].indexOf(char) != -1)
str += ad[i] + "<br/>";
con.innerHTML = str+'\n
See Demo
Updated
See the below demo give your search string it shows like a search engine optimize your code for your convenience.
Demo 2

jQuery removing values from a comma separate list

Given an input like:
<input type="test" value="3,4,9" />
What's the best way to remove a value like 9, 4 or 3, without having issues with the commas, I don't want this ending up:
value="3,4,"
value="3,,9"
value=",4,9"
Is there a clean way to get this done in JavaScript/jQuery?
You could split your value into an array, then filter out values you do not want.
$("input[type='test']").val().split(",") // ["3","4","9"]
.filter(function(v){return !isNaN(parseInt(v))}) // filter out anything which is not 0 or more
Here is a less terse version which filters out anything which is not numeric
var array = $("input[type='test']").val().split(",");
// If you are dealing with numeric values then you will want
// to cast the string as a number
var numbers = array.map(function(v){ return parseInt(v)});
// Remove anything which is not a number
var filtered = numbers.filter(function(v){ return !isNaN(v)});
// If you want to rejoin your values
var joined = filtered.join(",");
Finally change the value on the input
$("input[type='test']").val(joined);
Similar to PHP implode/explode functions
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
var explode = value.split(',');
explode.remove(1);
var implode = explode.join(',');
Documentation:
fce: Split
fce: Join
fce: Array.remove
No jQuery required :P
<script type="text/javascript">
//var subject = '3,4,9';
//var subject = '3,,9';
var subject = ',,4,9';
var clean = Array();
var i = 0;
subject = subject.split(',');
for (var a in subject)
{
if(subject[a].length)
{
clean[i] = subject[a];
i++;
}
}
document.write(clean.join(','));
</script>
You may also use pure javascript. Let say you want to take off only "4":
value = value.replace(/4,?/, '')
or "3" and "9":
value = value.replace(/([39],?)+/, '')
I think this function will work for what you are trying to do: http://www.w3schools.com/jsref/jsref_split.asp
string.split(separator, limit)
use
array = string.split(separator);
to break a string into an array. then use this to join after manipulations.
string = array.join(separator);
var ary = value.split(',');
ary.splice(indexOfItemToRemove,1)
var result = ary.join(',');
This is discussed in another post:
remove value from comma separated values string
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(",");
for(var i = 0 ; i < values.length ; i++) {
if(values[i] == value) {
values.splice(i, 1);
return values.join(",");
}
}
return list;
}
You can use this function:
function removeComma(x) {
var str = '';
var subs = '';
for(i=1; i<=x.length; i++) {
subs = x.substring(i-1, i).trim();
if(subs !== ',') {
str = str+subs;
}
}
return str;
}

Categories

Resources