How to extract expected value from string, html input submission - javascript

Is there a way to extract an expected value from a string within an html input submission?
If the following is a single submission, and its parts delimited by double quotes here only for clarity, is there a way to set the expected value, as well as the trailing string, to variables?:
"expected-value" "second part of same input string, the quotes arent real"
ex.
var exp = "expected-value";
var trail = "second part of same input string, the quotes arent real";
Upon input submission how to parse string and extract each and to their variables?

Use Javascripts split method and a proper delimiter and you can 'split' the string into an array, and then access the different parts of the array.
I would avoid the double quotes. You'll have to figure out how and where your delimiter is, but split is pretty flexible in those regards.
$text = "expected-value|second part of same input string, the quotes arent real";
result = $text.split('|');
var exp = result[0];
var trail = result[1];
console.log(exp);
console.log(trail);
// output:
// expected-value
// second part of same input string, the quotes arent real
To get the value from a text input you would use something like:
document.getElementById('textbox_id').value
Split method documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

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

replace "<0x00>" in string

Currently, I am having a problem with a string that I received after sending the command line containing the <0x00> character so how can I remove it from the string?
For example, my var string is:
<0x00>
awplus #
output:
awplus #
Use the following code to get your desired output
var string = "<0x00> awplus #";
string = string.replace("<0x00>", '');
string = string.trim();
document.write (string);
You can simply use split function and pass the string value you want to remove and then select the required part. Please note that split function returns array of string after spliting the original. You must choose the required value from the array.
I've used trim() to remove spaces around the resulting value.
Execute the following code in browser's developer console and you'll get the output.
var str = "<0x00> awplus #";
console.log(str.split('<0x00>')[1].trim());

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.

how to remove first special character from string

I have values seperated by pipes in a database. But the issue is that I am appending | at every entry.
For Example:
|275634|374645|24354|
How can I remove the first pipe from the whole string not all the pipes.
Once inserted I don't need to check for the next time when it updates.
If I use substring(1) then it will remove the first character every time,
Please suggest a fix?
//input = '|275634|374645|24354|';
output = input.replace('|', '');
String#replace will replace the first occurance in a String. If you replace it with an empty String '' it is removed.
jsFiddle
you can use substring(index) method where ever you want to remove the perticular special character from the String: like
String str2 = "|275634|374645|24354|";
str2 = str2.substring(1);
System.out.println(str2);
you can see the output as 275634|374645|24354|

Categories