I got following string which I'd like to be an array:
"["Arr1","Arr2"]"
I need to remove first and last chars in order to have
["Arr1","Arr2"].
I was trying with slice function like that:
var result = arr.slice(1, -1) but I got ""Arr1","Arr2"".
Any ideas how to handle it?
To convert from string to that array use JSON.parse(json_string), this does not have anything to do with removing characters from string.
Related
I don't understand this behaviour:
var string = 'a,b,c,d,e:10.';
var array = string.split ('.');
I expect this:
console.log (array); // ['a,b,c,d,e:10']
console.log (array.length); // 1
but I get this:
console.log (array); // ['a,b,c,d,e:10', '']
console.log (array.length); // 2
Why two elements are returned instead of one? How does split work?
Is there another way to do this?
You could add a filter to exclude the empty string.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(function(el) {return el.length != 0});
A slightly easier version of #xdazz version for excluding empty strings (using ES6 arrow function):
var array = string.split('.').filter(x => x);
This is the correct and expected behavior. Given that you've included the separator in the string, the split function (simplified) takes the part to the left of the separator ("a,b,c,d,e:10") as the first element and the part to the rest of the separator (an empty string) as the second element.
If you're really curious about how split() works, you can check out pages 148 and 149 of the ECMA spec (ECMA 262) at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Use String.split() method with Array.filter() method.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(item => item);
console.log(array); // [a,b,c,d,e:10]
console.log (array.length); // 1
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split
trim the trailing period first
'a,b,c,d,e:10.'.replace(/\.$/g,''); // gives "a,b,c,d,e:10"
then split the string
var array = 'a,b,c,d,e:10.'.replace(/\.$/g,'').split('.');
console.log (array.length); // 1
That's because the string ends with the . character - the second item of the array is empty.
If the string won't contain . at all, you will have the desired one item array.
The split() method works like this as far as I can explain in simple words:
Look for the given string to split by in the given string. If not found, return one item array with the whole string.
If found, iterate over the given string taking the characters between each two occurrences of the string to split by.
In case the given string starts with the string to split by, the first item of the result array will be empty.
In case the given string ends with the string to split by, the last item of the result array will be empty.
It's explained more technically here, it's pretty much the same for all browsers.
According to MDN web docs:
Note: When the string is empty, split() returns an array containing
one empty string, rather than an empty array. If the string and
separator are both empty strings, an empty array is returned.
const myString = '';
const splits = myString.split();
console.log(splits);
// ↪ [""]
Well, split does what it is made to do, it splits your string. Just that the second part of the split is empty.
Because your string is composed of 2 part :
1 : a,b,c,d,e:10
2 : empty
If you try without the dot at the end :
var string = 'a,b,c:10';
var array = string.split ('.');
output is :
["a,b,c:10"]
You have a string with one "." in it and when you use string.split('.') you receive array containing first element with the string content before "." character and the second element with the content of the string after the "." - which is in this case empty string.
So, this behavior is normal. What did you want to achieve by using this string.split?
try this
javascript gives two arrays by split function, then
var Val = "abc#gmail.com";
var mail = Val.split('#');
if(mail[0] && mail[1]) { alert('valid'); }
else { alert('Enter valid email id'); valid=0; }
if both array contains length greater than 0 then condition will true
Actually I'm getting the arraylist from android device in node.js . But as it's in string form so I wanna convert it into an array . For that I've referred a lot of similar questions in SO but none of them were helpful . I also tried to use JSON.parse() but it was not helpful.
I'm getting societyList in form '[Art, Photography, Writing]'.Thus how to convert this format to an array?
Code:
var soc_arr=JSON.parse(data.societyList)
console.log(soc_arr.length)
use something like this
var array = arrayList.replace(/^\[|\]$/g, "").split(", ");
UPDATE:
After #drinchev suggestion regex used.
regex matches char starts with '[' and ends with ']'
This string is not valid JSON since it does not use the "" to indicate a string.
The best way would be to parse it yourself using a method like below:
let data = '[test1, test2, test3]';
let parts = data
.trim() // trim the initial data!
.substr(1,data.length-2) // remove the brackets from string
.split(',') // plit the string using the seperator ','
.map(e=>e.trim()) // trim the results to remove spaces at start and end
console.log(parts);
RegExp.match() maybe
console.log('[Art, Photography, Writing]'.match(/\w+/g))
So match() applies on any string and will split it into array elements.
Use replace and split. In addition, use trim() to remove the trailing and leading whitespaces from the array element.
var str = '[Art, Photography, Writing]';
var JSONData = str.replace('[','').replace(']','').split(',').map(x => x.trim());
console.log(JSONData);
I am trying to achieve wild card search on a string array using java script
Here the wild cards i use are ? -to represent single char and * to represent multiple char
here is my string array
var sample = new Array();
sample[0] = 'abstract';
sample[1] = 'cabinet';
sample[2] = 'computer';
For example i searched for a string 'ab*t' in the array and the regular expression I used for this is '\ab.*t\', but the problem is I get both 'abstract' and 'cabinet' as matching strings. I only want the string that starts with 'ab' and not where it comes in the middle.
So I modified my regexp like this '\^ab.*t$\ but still the same result. So can somebody give me some tips on how this can be achieved.
You are using using wrong wrong slashs you should use forward slash('/') instead of backward slashs ('\')
probably it'll help you /^ab.*t$/
I have a variable which contains the values like this ..
["09:09:49", "00:14:09", "00:05:50", "02:38:02", "01:39:28"]
Now as per my need i have to formate like this ..
[09:09:49, 00:14:09, 00:05:50, 02:38:02, 01:39:28]
for this i tried
callduration=[];
callduration=["09:09:49", "00:14:09", "00:05:50", "02:38:02", "01:39:28"];
var newstring = callduration.replace(/\"/g,'');
But it is giving error ..
TypeError: callduration.replace is not a function
var newstr=callduration.replace(/\"/g,'');
Please help me.
Thanks in advance..
First off, you must note that callduration is an array. Arrays do not have a replace method, hence the error.
As mentioned by #Felix Kling, the quotes are just string delimiters. They are not part of the string values contained in your array of strings. For example, when accessing callduration[0] you will get a string containing the 09:09:49 sequence of characters.
However, if you really need a string in the requested format, here it is:
var callduration = ["09:09:49", "00:14:09", "00:05:50", "02:38:02", "01:39:28"];
var newstr = '[' + callduration.join(', ') + ']';
newstr; //"[09:09:49, 00:14:09, 00:05:50, 02:38:02, 01:39:28]"
Though this probably won't be of much use unless you have some very specific use case in mind.
callduration is an array. That means it contains a sequential, ordered list of items. Those items must be something that can exisdt in javascript. As your array exists like this:
["09:09:49", "00:14:09", "00:05:50", "02:38:02", "01:39:28"]
it is an array of strings. Each time value is represented by its own string. The quote marks are not actually part of the string - that' just how a string is represented when typing it.
If you want the array to be an array of something other than strings, you would need to specify what data type you want it to be. 09:09:49 as you've asked, it not a legal javascript piece of data.
Some choices that you could use:
An array of numbers where each number represents a time value (say milliseconds since midnight).
An array of Date objects.
If you have an array of strings now and you wanted to convert it to either of the above, you would loop through your existing array, parse the string you have now into an actual numeric time and then convert that into whatever numeric or object format you want to be in the array.
Ok, So I hit a little bit of a snag trying to make a regex.
Essentially, I want a string like:
error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z
to be parsed to read
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
ateTo=2013-01-16T05:00:00.000Z
So I want it to pull known keywords, and ignore other strings that have =.
My current regex looks like this:
(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=[\w\s\f\-\:]+(?![(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=])
So I'm using known keywords to be used dynamically so I can list them as being know.
How could I write it to include this requirement?
You could use a replace like so:
var input = "error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z";
var result = input.replace(/\s*\b((?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/g, "\n$1");
result = result.replace(/^\r?\n/, ""); // remove the first line
Result:
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
dateTo=2013-01-16T05:00:00.000Z
Another way to tokenize the string:
var tokens = inputString.split(/ (?=[^= ]+=)/);
The regex looks for space that is succeeded by (a non-space-non-equal-sign sequence that ends with a =), and split at those spaces.
Result:
["error=some=new item", "user=max", "dateFrom=2013-01-15T05:00:00.000Z", "dateTo=2013-01-16T05:00:00.000Z"]
Using the technique above and adapt your regex from your question:
var tokens = inputString.split(/(?=\b(?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/);
This will correctly split the input pointed out by Qtax mentioned in the comment: "error=user=max foo=bar"
["error=", "user=max foo=bar"]