how to check next existence of a character in string in javascript - javascript

Hi All I have a string like this
var data='mobile,car,soap,room';
I am parsing from this string and making this string as comma sperated and pushing it into an array like this
var availableTags=[];
var str='';
for(i=0;i<data.length;i++)
{
if(data[i]==',')
{
availableTags .push(str);
str='';
}
else
{
str +=data[i];
}
}
But I am doing wrong as I cannot get the last value after comma... Now What I want to ask how can I come to know the next existence of , in my string that whether it exists or not. So that I can also include the last value.
I would also appreciate if someone guide me that how can I accomplish that same task some other way.
I want the string to be an array and it should look like this
["mobile","car","soap","room"]

you can use
var availableTags = data.split(",");
it will handle all the things. and will result in an array.

You can use:
data.split(/,/)
See the split documentation.

After loop, you need to check value of str and add it too. It can contain the rest after last comma, or it can be empty in case comma was the last character in data.
But as other pointed, split is probably better way to do it.

As far as fixing your existing function, try adding the following after the for loop:
if (str != "")
availableTags.push(str);
(When the loop ends str holds whatever came after the last comma.)
But like the other answers said, you can just use the array .split() method:
var availableTags = data.split(",");

You could append an extra comma on at the start:
data = data + ","
...

Related

javascript split string function not working

I am trying to split a string:
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
var res = device_data.split('*');
But it's not working. it's just displaying this string
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
var res = str.split('*');
console.dir(res)
,HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#,HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555
Instead of creating an array with two elements.
IMHO, you want something like this:
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
splitStrArr = str.split('*').filter(str => str != "")
console.log(splitStrArr)
console.log(splitStrArr[0])
console.log(splitStrArr[1])
You are getting a string with a period in the beginning because whatever you are doing leads to the result of String#split being converted to a string. String#split returns an array. An array converted to a string is of the form of element0,element1,element2 ... elements separated by commas.
The result of String#split in your case is ["",...] with 3 elements since your string begins with the character '*' you are searching, so String#split will create an empty string as the first element of the returned array. So the result is exactly as expected, and String#split is working as intended.
get rid of the first character of the string,
mystring.substr(1).split('*')
get rid of the empty strings
mystring.split('*').filter(s=>s!='')
to obtain the desired result.
You can use:
var res = str.split("#");
You can check in Javascript console in browser itself.
As a suggestion/ idea, you can always use the browser console, for example, Chrome browser, to execute simple scripts like these.
This way, you can save time, as it is easier to check your data structures, their internal data.
If you try
var res = str.split('*');
you obtain three elements:
res[0] is '' (empty string)
res[1] is 'HQ,61...'
res[2] is 'HQ,...'

how to remove First text from string in jquery?

var selectedCustomers = document.getElementById("hfCustomerID");
output :- "|1|2|3"
this is my hidden field in which pushed value stored.
values in hidden field are stored "|1|2|3" like this
because of this when string is split and pushed in array at index 0 =
"" is stored.
how to check and remove First "|" from string in jquery before pushing it to array?
"|1|2|3".slice(1).split('|');
use slice() to remove the first character.
"|1|2|3".match(/[^|]/g);
or use Regx
You can use substr to remove the first char like this,
string.substr(1);
console.log("|1|2|3".substr(1).split('|'));
You can use substring to remove first character from string.
var trimmed = "|1|2|3".substring(1);
alert (trimmed)
This can be done in multiple ways.
If value is always expected like you mentioned then can use string.substr(1).split('|') as suggested in one of the answer, else you can do it using "filter".
selectedCustomers.split('|').filter(function(value) {
return value !== "" && value !== null;
});
console.log("|1|2|3".slice(1).split('|'));
The following way you can do this.
trimmed= "|1|2|3".substring(1).split('|');
alert(trimmed);
Please refer to the code below:
var selectedCustomers = document.getElementById("hfCustomerID").substring(1);

Javascript String Split

I've a String like following:
var str = '35,35,105,105,130,208,50,250';
I would like to split this string and get like this:
var arr = [[35,35],[105,105],[130,208],[50,250]];
I tried some ways, but none of them give me anything. I tried with looping to find the even comma position and split, but that doesn't seem good to me. Please give me some suggestion on this. I'm looking for RegEx Solution.
One possible approach:
'35,35,105,105,130,208,50,250'.match(/\d+,\d+/g).map(function(s) {
return s.split(',');
});
Another crazy idea in one line:
JSON.parse('['+ '35,35,105,105,130,208,50,250'.replace(/\d+,\d+/g, '[$&]') +']');
Here's one way to do it.
var values = str.split(','),
output = [];
while(values.length)
output.push(values.splice(0,2));
If str contains an odd number of values, the last array in output will contain only one value using this method.

Javascript RegExp matching returning too many

I need to take a string and get some values from it. I have this string:
'tab/tab2/tab3'
The '/tab3' is optional so this string should also work:
'tab/tab2'
I currently am trying this which works for the most part:
'tab/tab2/tab3'.match(new RegExp('^tab/([%a-zA-Z0-9\-\_\s,]+)(/([%a-zA-Z0-9-_s,]+)?)$'));
This will return:
["tab/tab2/tab3", "tab2", "/tab3", "tab3"]
but I want it to return
["tab/tab2/tab3", "tab2", "tab3"]
So I need to get rid of the 3rd index item ("/tab3") and also get it to work with just the 'tab/tab2' string.
To complicate it even more, I only have control over the /([%a-zA-Z0-9-_s,]+)? part in the last grouping meaning it will always wrap in a grouping.
you don't need regex for this, just use split() method:
var str = 'tab/tab2/tab3';
var arr = str.split('/');
console.log(arr[0]); //tab
console.log(arr[1]); //tab2
jsfiddle
I used this regexp to do this:
'tab/tab2/tab3'.match(new RegExp('^tab/([%a-zA-Z0-9\-\_\s,]+)(?:/)([%a-zA-Z0-9-_s,]+)$'));
Now I get this return
["tab/tab2/tab3", "tab2", "tab3"]
Now I just need to allow 'tab/tab2' to be accepted aswell...
Do not put regex between " or ', using /g to make global search else only first occurrence is returned
"tab/tab2/tab3".match(/tab[0-9]/g)

Splitting string in javascript

How can I split the following string?
var str = "test":"abc","test1":"hello,hi","test2":"hello,hi,there";
If I use str.split(",") then I won't be able to get strings which contain commas.
Whats the best way to split the above string?
I assume it's actually:
var str = '"test":"abc","test1":"hello,hi","test2":"hello,hi,there"';
because otherwise it wouldn't even be valid JavaScript.
If I had a string like this I would parse it as an incomplete JSON which it seems to be:
var obj = JSON.parse('{'+str+'}');
and then use is as a plain object:
alert(obj.test1); // says: hello,hi
See DEMO
Update 1: Looking at other answers I wonder whether it's only me who sees it as invalid JavaScript?
Update 2: Also, is it only me who sees it as a JSON without curly braces?
Though not clear with your input. Here is what I can suggest.
str.split('","');
and then append the double quotes to each string
str.split('","'); Difficult to say given the formatting
if Zed is right though you can do this (assuming the opening and closing {)
str = eval(str);
var test = str.test; // Returns abc
var test1 = str.test1; // returns hello,hi
//etc
That's a general problem in all languages: if the items you need contain the delimiter, it gets complicated.
The simplest way would be to make sure the delimiter is unique. If you can't do that, you will probably have to iterate over the quoted Strings manually, something like this:
var arr = [];
var result = text.match(/"([^"]*"/g);
for (i in result) {
arr.push(i);
}
Iterate once over the string and replace commas(,) following a (") and followed by a (") with a (%) or something not likely to find in your little strings. Then split by (%) or whatever you chose.

Categories

Resources