Correct format structure creating variables - javascript

Is it ok to create vars with spaces and forward slashes?
Like so:
var PICKUPS / TRUCKS = {};

No, variable names cannot have spaces, but some special characters are allowed.
To reference the list of valid characters you can refer to this answer.
In your case, this is invalid in Javascript:
// INVALID!
var PICKUPS / TRUCKS = {};
First, the / operator is the divide operator, so the Javascript interpreter will look at this like a Mathematical operation, trying to "divide PICKUPS with TRUCKS", which will cause an error, especially after the var keyword, it won't know how to make sense of that (for example, first it will see that you are trying to create a variable, and then it will see that instead of creating a variable, you are trying to do some math, which will confuse the javascript interpreter).
But you can do something like this:
// Valid Javascript; No spaces or illegal characters
var pickups_trucks = {};
Also, if the names are embedded in javascript objects, you can name objects using string identifiers, where anything legal in a string can work:
var Automobiles = {
"Trucks & Pickups": [],
"Three Wheelers": []
};
console.log(Automobiles["Trucks & Pickups"]);
Hope this helps!

No, this is NOT VALID variable name in javascript. It cannot have spaces or forward slash in it.
Here https://mothereff.in/js-variables you can test if your variable name is valid or not

This is invalid javascript.
I recommend you declare variables separately like such:
var PICKUPS = 0,
TRUCKS = {};
I recommend you use a tool like JSLint or JSHint to verify you code.

In any programming language its not a good idea to use spaces or slashes in your variable names. There are several ways to write vars using underscores, camel case or snake case are just a few.

Related

Regex substitution '$1' - why is it a string?

Silly question, but I'll ask it anyway: Why is the substitution part of a regular expression in JavaScript encompassed in quotes as a string, where it seems to be a variable in its own right? eg '$2'
alert("banana split") // nana split
function reg(afilename)
{
var rexp = new RegExp(/^(ba)(.+)/gim)
var newName = afilename.replace(rexp, '$2')
return newName
}
Because it's not a [Javascript] variable in its own right.
If you didn't single-quote it, JavaScript would try to pass the value of the variable $2 as an argument (yes, you can give JavaScript variables names starting with $), except you don't have one.
This way, the Regex engine gets the actual, literal string $2, and gives it its own special meaning.
It's a perfect example of abstraction, where you can witness two "layers" of software interacting. Consider also document.write('<p>Text</p>'); — you wouldn't want JavaScript to try to parse that HTML, right? You want to pass it verbatim to the entity that is going to handle it.

Javascript easy array declartion option like perl

In perl we can declare the array with qw or quote word take make each word is taken into individual array cell.
eg.
my #arr= qw( hello
world)
or else you need to quote each word
eg
my #arr = ("hello" , "word");
Is there something similar in javascript as sometime it need lot of formatting to simple declare array.
This is what you need, for this specific case: const arr = 'hello world'.split(' ');.
Edit:
Check out the docs for String.split on MDN. Also, read something on types in JavaScript, if you are wondering why it is possible to call this method on string literal, as I did.

Remove slashes from string using RegEx in JavaScript

I am trying to remove all special characters except punctuation from a customer complaint textarea using this code:
var tmp = complaint;
complaint = new RegExp(tmp.replace(/[^a-zA-Z,.!?\d\s:]/gi, ''));
but it keeps placing "/" in front, and in back of the string after sanitizing.
Example:
Hi, I h#ve a% probl&em wit#h (one) of your products.
Comes out like this
/Hi, I have a problem with one of your products./
I want
Hi, I have a problem with one of your products.
Thanks in advance for any help given.
The variable complaint is converted to a regular expression because you use the RegExp() constructor.
This probably isn't what you want. (I assume you want complaint to be a string).
Strings and regular expressions are two completely different data types.
Your output demonstrates how JavaScript displays regular expressions (surrounded by / characters).
If you want a string, don't create a regular expression (i.e. remove the RegExp constructor).
In other words:
complaint = complaint.replace(/[^a-zA-Z,.!?\d\s:]/gi, '');
You don't need the RegExp constructor:
complaint = tmp.replace(/[^a-zA-Z,.!?\d\s:]/gi, '');

Parsing malformed JSON in JavaScript

Thanks for looking!
BACKGROUND
I am writing some front-end code that consumes a JSON service which is returning malformed JSON. Specifically, the keys are not surrounded with quotes:
{foo: "bar"}
I have NO CONTROL over the service, so I am correcting this like so:
var scrubbedJson = dirtyJson.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2": ');
This gives me well formed JSON:
{"foo": "bar"}
Problem
However, when I call JSON.parse(scrubbedJson), I still get an error. I suspect it may be because the entire JSON string is surrounded in double quotes but I am not sure.
UPDATE
This has been solved--the above code works fine. I had a rogue single quote in the body of the JSON that was returned. I got that out of there and everything now parses. Thanks.
Any help would be appreciated.
You can avoid using a regexp altogether and still output a JavaScript object from a malformed JSON string (keys without quotes, single quotes, etc), using this simple trick:
var jsonify = (function(div){
return function(json){
div.setAttribute('onclick', 'this.__json__ = ' + json);
div.click();
return div.__json__;
}
})(document.createElement('div'));
// Let's say you had a string like '{ one: 1 }' (malformed, a key without quotes)
// jsonify('{ one: 1 }') will output a good ol' JS object ;)
Here's a demo: http://codepen.io/csuwldcat/pen/dfzsu (open your console)
something like this may help to repair the json ..
$str='{foo:"bar"}';
echo preg_replace('/({)([a-zA-Z0-9]+)(:)/','$1"$2"${3}',$str);
Output:
{"foo":"bar"}
EDIT:
var str='{foo:"bar"}';
str.replace(/({)([a-zA-Z0-9]+)(:)/,'$1"$2"$3')
There is a project that takes care of all kinds of invalid cases in JSON https://github.com/freethenation/durable-json-lint
I was trying to solve the same problem using a regEx in Javascript. I have an app written for Node.js to parse incoming JSON, but wanted a "relaxed" version of the parser (see following comments), since it is inconvenient to put quotes around every key (name). Here is my solution:
var objKeysRegex = /({|,)(?:\s*)(?:')?([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*)(?:')?(?:\s*):/g;// look for object names
var newQuotedKeysString = originalString.replace(objKeysRegex, "$1\"$2\":");// all object names should be double quoted
var newObject = JSON.parse(newQuotedKeysString);
Here's a breakdown of the regEx:
({|,) looks for the beginning of the object, a { for flat objects or , for embedded objects.
(?:\s*) finds but does not remember white space
(?:')? finds but does not remember a single quote (to be replaced by a double quote later). There will be either zero or one of these.
([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*) is the name (or key). Starts with any letter, underscore, $, or dot, followed by zero or more alpha-numeric characters or underscores or dashes or dots or $.
the last character : is what delimits the name of the object from the value.
Now we can use replace() with some dressing to get our newly quoted keys:
originalString.replace(objKeysRegex, "$1\"$2\":")
where the $1 is either { or , depending on whether the object was embedded in another object. \" adds a double quote. $2 is the name. \" another double quote. and finally : finishes it off.
Test it out with
{keyOne: "value1", $keyTwo: "value 2", key-3:{key4:18.34}}
output:
{"keyOne": "value1","$keyTwo": "value 2","key-3":{"key4":18.34}}
Some comments:
I have not tested this method for speed, but from what I gather by reading some of these entries is that using a regex is faster than eval()
For my application, I'm limiting the characters that names are allowed to have with ([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*) for my 'relaxed' version JSON parser. If you wanted to allow more characters in names (you can do that and still be valid), you could instead use ([^'":]+) to mean anything other than double or single quotes or a colon. You can have all sorts of stuff in here with this expression, so be careful.
One shortcoming is that this method actually changes the original incoming data (but I think that's what you wanted?). You could program around that to mitigate this issue - depends on your needs and resources available.
Hope this helps.
-John L.
How about?
function fixJson(json) {
var tempString, tempJson, output;
tempString = JSON.stringify(json);
tempJson = JSON.parse(tempString);
output = JSON.stringify(tempJson);
return output;
}

JavaScript RegExp: R naming conventions

We're all familiar with naming conventions in R (if not: Venables & Smith - Introduction to R, Chapter 1.8). Regular expressions, on the other hand, remain terra incognita and the most hated part in my programming life so far ... Recently, I've officially started JavaScript recapitulation, and I'm trying to create precise RegExp to check correct R object name.
Brief intro:
Object names must start with . or lower/uppercase letter, and if they start with . cannot continue with numeric... afterward, alphanumeric symbols are allowed with . and underscore _.
Long story short, here's my JS code:
var txt = "._.";
var inc = /^\.(?!\d)|^[a-z\.]/i;
document.write(inc.test(txt));
This approach manages the first part (. and/or lower/upper case and numeric after .), but I cannot pass something like & [\w\.]. I can write a function that will take care of this one, but is it at all possible to manage this with a single RegExp?
I'm not familiar with R or its naming conventions, but I'll give it a shot:
If you're only trying to verify that the name begins correctly, all you need to do is remove the \. from the character class, leaving you with: /^\.(?!\d)|^[a-z]/i. Otherwise, the . may still be the first character with no restrictions on the remaining ones.
If you want to verify the that entire name is correct, something like this should work:
/^(?:\.(?!\d)|[a-z])[a-z0-9_\.]+$/i

Categories

Resources