Slice off and store prefix of string in-place - javascript

In my former life, I worked with a couple of languages that used to have a string "slice" option where I could literally "slice" out part of the string and save the sliced out part into another variable.
In JS for example, I want to be able to remove the first 2 positions from a string and store that value into another variable.
It would appear in JS that to accomplish the same thing requires two steps.
var twoDigits = myString.slice(0, 2);
myString = myString.substring(2);
Is there a better way to do this without resorting to writing my own function?

Related

How to hide or encrypt a query string variable

How can i make the variable 'success' that is passed to 'payment_success.php' below to be somehow encrypted, i don't want the user to know the exact variable name passed. i wanted using post method, but i can't use it for my call back function. Any idea will be a great help
callback: function(response){
const referenced = response.reference;
window.location.href='payment_success.php?success='+referenced;
},
The following is one of tricks I used in a project trying to hide a piece of data.
Assuming your string variable is "123abc".
You may first add a random suffix of three characters , so the string can be:
AC1 C8D E9u Z77 Vux
After that you may use a further trick to put your code "123abc" into a format like the following
1[3 random characters]2[4 random characters]3a[2 random characters]bc[3 random characters]
So the result of 123abc will be like
XXX1XXX2XXXX3aXXbcXXX
so can be any one of the following:
56f134a2rxxq3a43bcccd
97z1zux289873a5tbczwq
Eu11qzv2739u3auubc76x
and so on....
After passing to your PHP script, please extract the correct data.
If you want to be safer, split the characters more further apart by inserting longer random characters in between.
You may use further imagination to do the trick. For example, generate a string which can be random in length of the "mixing codes".

Best way to concatenate multiple strings?

I have a project, where user can put in drop-down values that can be selected. One can select multiple values at a time. So, we have to store the selection and get it on edit mode.
First thought
Let's store them as comma separated in DB.
f.e.
If suggestions are A , B , C and user selects A and B, I was going to store A,B in DB and while getting back the value split it with comma.
Problem arises when user has genuine "comma" in the field, for an instance first,option & second,option. At that time joining with comma won't work.
Second thought
I can think of another option to store it in a stringified array format and parse it while getting back.
For the above instance, it would store the data as ["first,option","second,option"]. It seems to be a good (and only) option for me.
Even though I have a bit of hesitation doing so (which lead me questioning here!) because my users can access the api/DB value directly and for them it doesn't look good.
So, Is there any other way to address this issue to benefit both parties, developers and users? Thanks in advance!!
I'd suggest using a standardized format such as JSON, XML etc.
Serialize and parse and with a widely used library so all escaping of reserved / special characters is done for you. Rolling your own here will cause you problems!
Better yet, use different fields for each suggestion, this is a better design in general. As long as the number of potential fields is finite this will work, e.g. 1-10 suggestions.
If you're going down the JSON route, we can do this in JavaScript like this:
let suggestions = ['Choice A, commas are not, a problem, though punctuation is.', 'Choice B', 'Choice C'];
let json = JSON.stringify(suggestions);
// Save to DB
saveToDB(json);
let jsonFromDB = loadFromDB();
let deserializedSuggestions = JSON.parse(jsonFromDB);
console.log(deserializedSuggestions);
we use semicolon (;) for this exact use case in our current project.
So, as per your question, they will be stored in the DB as option1;option2;option3
and when we get it back from the DB we can use the split() method on it to convert it into an array of substrings.
var str = "option1;option2;option3";
var res = str.split(";");
console.log(res);
which would result in (3) ["option1", "option2", "option3"] in the console.
hope this helps.

Javascript string->int injective function

I want to create a unique ID to a given string while the same ID should be received for that string every time i'm trying to do that, and two different strings should get different IDs.
Let say the size of the strings is limited to x chars, and therefor this injective function is possible.
Are you familiar with a javascript function or a suitable algorithm that would be good fot it?
Thanks in advance.

JSON.parse & JSON.stringify handling long integers as strings

I have the problem, that I need to parse long integers in my API. Since I don't do anything arithmetically, it is the easiest to handle them as Strings. I tried Bignumber.js, but it starts complaining if numbers are longer than 15 characters. Unfortunately I have to handle them as well.
Since I don't do anything arithmetically with it and actually even store those numbers as String I would like a JSON Parser that parses too big numbers as Strings and is capable of also treat them as numbers in JSON.stringify.
I tried the stringify with a replacer function, but I could not get rid of the quotes around my number.
I also did not find a library, that just takes care of this issue.
Edit / Clarification
I want my big number to be a String in javascript, but a number in JSON (after JSON.stringify)
e.g. Object in Javascript
var myObj = {
id: "89074987798719283473" // <-- String within javascript
}
var objString = JSON.stringify(myObj)
Now my objString should be
{id: 89074987798719283473}
And NOT
{id: "89074987798719283473"}
If you absolutely must do this and really can't find a better place to handle this, then remember that JSON is just a string, and all the tools for string manipulation can be brought to bear on this problem. So you could do something like:
var myObj = {
id: "89074987798719283473" // <-- String within javascript
}
var json = JSON.stringify(myObj); // this is {"id":"89074987798719283473"}
var numberJson = json.replace(/"id":"(\d+)"/,'"id":$1'); // this is now {"id":89074987798719283473}
console.log(numberJson);
Of course this is hacky and error prone as you have to be very careful about what you are matching (you might have other properties called id nested in your json that you don't want manipulated). If you wanted to make it a little more robust, you could append something the end of your id before you stringify to make it easier to find and replace it in the string.

jQuery/JavaScript regex return matched text from string

I am trying to create a fairly complex system for my website. I want to be able to write some pseudo like code and then parse it to make it do something in my back-end.
My data is inside two $.each loops as this is an Object of data with multiple levels to it.
For instance, I want to take a string like this:
"<!this!> == <!PropertyStreetNumber!>"
Then how I would like for the above code to executed is this:
FormData[parentKey][this] == FormData[parentKey]["PropertyStreetNumber"]
Thanks for any help!
Here's some of my code, the code where this would need to go in (see commented area)
http://jsbin.com/liquvetapibu/1/
Is there any restriction not to use regular expressions on JavaScript?
You could do something like this:
var myString = "<!this!> == <!PropertyStreetNumber!>";
var aux = /<!(.*?)!> == <!(.*?)!>/.exec(myString);
The value of aux will be an array with 3 elements:
The string that was tested.
The first element within <! !>
The second element within <! !>
Then it would depend on what the content on each one is: in your example this is an object, while you seem to use PropertyStreetNumber as a string (maybe a typo?). If you want to use it as an object, you will have to use eval() (e.g.: eval(aux[1])) while if you want to use it as a string, you can use it directly (e.g.: aux[2]).
Conceptually, the first thing you would need to do is determine the type of statement you are working with. In this case, a comparison statement. So you need a regex statement to filter this into a "statement type".
Once you do that, you can figure out what the arguments are. So you create a regex to pull out the arguments on each side of the operator.
Next, the strings that represent action code items need to be parsed. The this argument is actually an object, whereas "PropertyStreetNumber" is a string. You've got to be able to determine which is which. Then you can filter that into a function that has been created specifically to handle those statements types.
If at all possible, I would try to avoid the use of eval(). You can get into trouble with it.
you could try with
var beg = str.indexOf("== <!") + 5;
to find the index of the beggining and then slice counting the chars from beginning like
str.slice(beg, -2);
and from there build the rest.
couldnt that work?`

Categories