How to remove double quotes from jquery array - javascript

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.

Related

Best practice for converting string to object in JavaScript

I am working on a small UI for JSON editing which includes some object and string manipulation. I was able to make it work, but one of the fields is bit tricky and I would be grateful for an advice.
Initial string:
'localhost=3000,password=12345,ssl=True,isAdmin=False'
Should be converted to this:
{ app_server: 'localhost:3000', app_password:'12345', app_ssl: 'True', app_isAdmin: 'False' }
I was able to do that by first splitting the string with the ',' which returns an array. And then I would loop through the second array and split by '='. In the last step I would simply use forEach to loop through the array and create an object:
const obj = {}
arr2.forEach((item) => (obj[`app_${item[0]}`] = item[1]));
This approach works, but in case some of the fields, i.e password contains ',' or '=', my code will break. Any idea on how to approach this? Would some advanced regex be a good idea?
Edit: In order to make things simple, it seems that I have caused an opposite effect, so I apologize for that.
The mentioned string is a part of larger JSON file, it is the one of the values. On the high level, I am changing the shape of the object, every value that has the structure I described 'server='something, password=1234, ssl=True', has to be transformed into separate values which will populate the input fields. After that, user modify them or simply download the file (I have separate logic for joining the input fields into the initial shape again)
Observation/Limitation with the design that you have :
As per your comment, none of the special characters is escaped in any way then how we will read this string password=12345,ssl=True ? It will be app_password: 12345,ssl=True or app_password: 12345 ?
why localhost=3000 is converted into app_server: 'localhost:3000' instead of app_localhost: '3000' like other keys ? Is there any special requirement for this ?
You have to design your password field in the way that it will not accept at least , character which is basically used to split the string.
Here you go, If we can correct the above mentioned design observations :
const str = 'localhost=3000,password=123=45,ssl=True,isAdmin=False';
const splittedStr = str.split(',');
const result = {};
splittedStr.forEach(s => {
const [key, ...values] = s.split('=')
const value = values.join('=');
result[`app_${key}`] = value
});
console.log(result);
As you can see in above code snippet, I added password value as 123=45 and it is working properly as per the requirement.
You can use a regular expression that matches key and value in the key=value format, and will capture anything between single quotes when the value happens to start with a single quote:
(\w+)=(?:'((?:\\.|[^'])*)'|([^,]+))
This assumes that:
The key consists of alphanumerical characters and underscores only
There is no white space around the = (any space that follows it, is considered part of the value)
If the value starts with a single quote, it is considered a delimiter for the whole value, which will be terminated by another quote that must be followed by a comma, or must be the last character in the string.
If the value is not quoted, all characters up to the next comma or end of the string will be part of the value.
As you've explained that the first part does not follow the key=value pattern, but is just a value, we need to deal with this exception. I suggest prefixing the string with server=, so that now also that first part has the key=value pattern.
Furthermore, as this input is part of a value that occurs in JSON, it should be parsed as a JSON string (double quoted), in order to decode any escaped characters that might occur in it, like for instance \n (backslash followed by "n").
Since it was not clarified how quotes would be escaped when they occur in a quoted string, it remains undecided how for instance a password (or any text field) can include a quote. The above regex will require that if there is a character after a quote that is not a comma, the quote will be considered part of the value, as opposed to terminating the string. But this is just shifting the problem, as now it is impossible to encode the sequence ', in a quoted field. If ever this point is clarified, the regex can be adapted accordingly.
Implementation in JavaScript:
const regex = /(\w+)=(?:'(.*?)'(?![^,])|([^,]+))/g;
function parse(s) {
return Object.fromEntries(Array.from(JSON.parse('"server=' + s + '"').matchAll(regex),
([_, key, quoted, value]) => ["app_" + key, quoted ?? (isNaN(value) ? value : +value)]
));
}
// demo:
// Password includes here a single quote and a JSON encoded newline character
const s = "localhost:3000, password='12'\\n345', ssl='True', isAdmin='False'";
console.log(parse(s));

Intersection of characters in two strings

I have an object with strings in it.
filteredStrings = {search:'1234', select:'1245'}
I want to return
'124'
I know that I can turn it into an array and then loop through each value and test if that value in inside of the other string, but I'm looking for an easier way to do this. Preferably with Lodash.
I've found _.intersection(Array,Array) but this only works with Arrays.
https://lodash.com/docs#intersection
I want to be able to do this without having to convert the object to an array and then loop through each value because this is going to be potentially holding a lot of information and I want it to work as quickly as possible.
Thank you for you help.
Convert one of the strings (search) to a RegExp character set. Use the RegExp with String#match on the other string (select).
Note: Unlike lodash's intersection, the result characters are not unique, so for example 4 can appear twice.
var filteredStrings = {search:'1234', select:'124561234'}
var result = (filteredStrings.select.match(new RegExp('[' + filteredStrings.search + ']', 'g')) || []).join('');
console.log(result);

Array operations java script

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.

Change javascript regex divider character

I have a simple JS question.
I have this code, and what I need is cut the textbox value every two characters (this works fine), but I want to change the comma with the column.
My actual result is:
stringtest - st,ri,ng,te,st
and I want this:
stringtest - st:ri:ng:te:st
my code is:
function test() {
var textboxtext= $("#textbox").val();
var splitted = textboxtext.match(/.{2}|.{1,2}/g);
alert("B8:27:EB:" + splitted)
The problem is not with the regex, but with how you're converting the result array to a string. When the JavaScript engine needs to convert an array to a string (which is done implicitly when you use the binary + operator with an string on either side), it calls the toString() method, which basically just calls the join() method, which returns a string with each element of the array converted to a string, and separated by commas.
But you can call the join method yourself and specify what character you'd like it to use as a separator, like this:
alert("B8:27:EB:" + splitted.join(':'));
On a side note, you can simplify your regex to .{1,2}, which is exactly the same as what you had previously:
var splitted = textboxtext.match(/.{1,2}/g);

JavaScript strings manipulations

I have a string like this below:
var stOrig= "ROAM-Synergy-111-222-LLX" ;
There can be any no. of "alphabetic" terms before numeric values 111-222..
There may or may not be any numeric values i.e the string can also be simply like this:
"ROAM-Synergy-LCD-ROAM".
if there are numeric values then I am using this
var myval = st.match(/^\D+(?=-)/)[0];
to get only the alphabetic terms before the numeric values. Its working fine till here.
But if suppose string does not contains any numeric values then my regular expression returns one less term i.e
Say the original string is: "ROAM-Synergy-LCD-ROAM" (without any numbers in it.)
Now if is use above reg expression...then it will return only "ROAM-Synergy-LCD"
..
so first I need to check for any numeric values in original string.. and if string contains numeric values then I use above reg exp...but please suggest If string does not contain numeric values then what reg expression to use..
Use
var myval = st.match(/^\D+(?=-|$)/)[0];
The $ matches at the end of the string.
See it live on regex101.com.

Categories