SyntaxError: missing ; before statement - javascript

I am getting this error :
SyntaxError: missing ; before statement
Why would I get that from this code? How can I get around this ?
var $this = $("input");
foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
}));

Looks like you have an extra parenthesis.
The following portion is parsed as an assignment so the interpreter/compiler will look for a semi-colon or attempt to insert one if certain conditions are met.
foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
})

too many ) parenthesis remove one of them.

Or you might have something like this (redeclaring a variable):
var data = [];
var data =

I got this error, hope this will help someone:
const firstName = 'Joe';
const lastName = 'Blogs';
const wholeName = firstName + ' ' lastName + '.';
The problem was that I was missing a plus (+) between the empty space and lastName. This is a super simplified example: I was concatenating about 9 different parts so it was hard to spot the error.
Summa summarum: if you get "SyntaxError: missing ; before statement", don't look at what is wrong with the the semicolon (;) symbols in your code, look for an error in syntax on that line.

Related

Node.JS not appending string weird bug?

function getStatementValue(view, statement){ // vars "#extends('parentview') ", 'extends'
var parentname = "";
view.replace(new RegExp(/\B#\w+\('([^(')\W]+)'\)\s/, 'm'), function(occurance){
parentname = occurance.replace('#' + statement + '(\'', '')
.replace('\')', "");
console.log(parentname) // parentview
console.log(parentname + 'test') // testntview <- unexpected result
});
return parentname;
}
I've got no clue to how that result is appearing.
when I add the string as shown in console.log, it replaces the string from the beginning, almost like it's re-assigning the memory space. Is this supposed to be happening? How do I return the correct parentviewtest result?
parentname = occurance.replace('#' + statement + '(\'', '')
.replace('\')', "").trim();
Solved it by adding a .trim() to the string modification. My input included invisible \r and \n characters that I was unaware of.
Thanks to #JaromandaX for spotting that out

Adding quotes to a comma separated string

What I have:
var a = "1.1.1.1,2.2.2.2,3.3.3.3"
What I need:
var a = '1.1.1.1','2.2.2.2','3.3.3.3'
What I'm trying:
var a = "1.1.1.1,2.2.2.2,3.3.3.3"
var b = a.split(",")
var c
for (var i=0;i<b.length; i++)
{
c.concat("\'").concat(b[i]).concat("\',\"")
}
What I'm actually getting with the above
"'1.1.1.1','"
I'm only able to get the first element right, how do I rectify this?
Also, in JS, is it even possible to have something like '1.1.1.1','2.2.2.2','3.3.3.3' stored in a variable?
A background to this problem:
I have an iframe whose source is a kibana query. The query in fact takes in values to a particular parameter in the above mentioned format.
Eg:
params:!('1.1.1.1','2.2.2.2')
While my db contains the param values as a string of CSV.
Eg.
"1.1.1.1,2.2.2.2,3.3.3.3"
Try this
var a = "1.1.1.1,2.2.2.2,3.3.3.3";
var b = "'" + a.split( "," ).join( "','" ) + "'";
console.log( b );
You don't need to deal with iterations for this, use a RegExp replace:
var a = "1.1.1.1,2.2.2.2,3.3.3.3";
var b = "'" + a.replace(/,/g, "','") + "'";
console.log( b );
The naive solution to your problem looks like this:
> line = '1.1.1.1,2.2.2.2,3.3.3.3'
'1.1.1.1,2.2.2.2,3.3.3.3'
> '"' + line.replace(/,/g, '","') + '"'
'"1.1.1.1","2.2.2.2","3.3.3.3"'
or if the quotes need to be reversed:
> "'" + line.replace(/,/g, "','") + "'"
'\'1.1.1.1\',\'2.2.2.2\',\'3.3.3.3\''
However, it sounds like what you need is a full-blown CSV parser, to handle cases in which you have quotes and commas and new lines and other crazy characters embedded in your input.
The naive solution seems to be in line, though, with what you were trying to do, and might illustrate why your approach fell short.
Your code works as you intended. Can you append to c without declaring?
var a = "1.1.1.1,2.2.2.2,3.3.3.3"
var b = a.split(",")
var c = ""
for (var i=0;i<b.length; b++)
{
c.concat("\'").concat(b[i]).concat("\',\"")
console.log(b)
}
You can store several values in a variables by using array for example.
If you want to get string like '"1.1.1.1","2.2.2.2","3.3.3.3"' you can use the following code:
var a = "1.1.1.1,2.2.2.2,3.3.3.3";
var b = a.split(',').map(function (str) {
return '"' + str+ '"';
}).join(',');
console.log(b);

How to replace a double 2 consecutive quotes by a space in JavaScript

I have a string which represents longitude/latitude in the following format:
dd°mm'ss''W (note 2 single quotes after ss).
And I am using the following code to transform the string in its decimal representation:
function dmsTodegrees(val) {
var s = val.replace('°', ' ');
s = s.replace("'", ' ');
s = s.replace("''", ' ');
var tokens = s.split(' ');
var result = Number.parseFloat(tokens[0]) + Number.parseFloat(tokens[1]) / 60 + Number.parseFloat(tokens[2]) / 3600;
if (tokens[3] === 'W' || tokens[3] === 'S') result = -result;
return result;
}
However, it seems that s = s.replace("''", ' '); is not doing what is intended, and the the 2 single quotes (') are not replaced by a space. Not sure what I am doing wrong here.
Note that i have omitted all the error handling here.
you can use /'{1,2}/g to replace all ' in the string. If you don't care about the number and want to replace all single quotes, you can just use /'+/g
function dmsTodegrees(val) {
var s = val.replace('°', ' ');
s = s.replace(/'{1,2}/g, ' ');
return s;
}
console.log(dmsTodegrees("dd°mm'ss''W"));
So, you are trying to replace °, ' and '' with space in order to split the string with space. Instead of replacing them with space and splitting the string with space, why don't you just split directly?
...
var tokens = val.split(/°|'{1,2}/);
...
It works like this:
"12.34°56.78'90.12''W".split(/°|'{1,2}/)
=> (4) ["12.34", "56.78", "90.12", "W"]
For these lines:
s = s.replace("'", ' ');
s = s.replace("''", ' ');
the first takes every "'" and replaces it with a space. So the second will never find two quotes together.
EXCEPT...replace only works on the first thing it finds.
so
"1,2,3,'',4,'',5,''".replace("'", " ").replace("''", ' ')
gives you
"1,2,3, ',4, ,5,''"
Check the answer from #Dij for the better way.
I would suggest to use single quotes (') with escape sequence(\') inside single quotes for replace function
function dmsTodegrees(val) {
var s = val.replace('°', ' ');
s = s.replace('\'', ' ');
s = s.replace('\'\'', ' ');
console.log(s);
var tokens = s.split(' ');
var result = Number.parseFloat(tokens[0]) + Number.parseFloat(tokens[1]) / 60 + Number.parseFloat(tokens[2]) / 3600;
if (tokens[3] === 'W' || tokens[3] === 'S') result = -result;
return result;
}
console.log(dmsTodegrees("20°10'30''4"));
You need to replace two single quotes first and then one single quote.
If you you repace the single quotes first, even two single quotes get replaced by two spaces (as is the case with you).
s = s.replace("''"," ");
s = s.replace("'"," ");

check if string is equal to a word and a number

I have an object that contains a string as a property. I want to check that this property is not equal to some word, followed by a space and a number. For instance, something like this:
var TheWordToCheck = "SomeWord";
if (TheObject['SomeProperty'] !== (TheWordToCheck + ' ' + 2)) {...}
if (TheObject['SomeProperty'] !== (TheWordToCheck + ' ' + 3)) {...}
In this example, the code checks for only "SomeWord 2" and "SomeWord 3". How can I simplify this where it checks any numbers?
Thanks.
You could use a regex and the match() method (untested)
var reg = new RegExp("^"+TheWordToCheck+"\\s\\d$")
if (!TheObject['SomeProperty'].match(reg) {...
FIDDLE
depends on the range of numbers you need to check, if it is static or is less than a maximum value, you can use a loop and append the loop variable with the string and check
for (var i=0;i<maxNumber;i++)
{
if (TheObject['SomeProperty'] !== (TheWordToCheck + ' ' + i)) {...
break;
}
}
or you can use regex as suggested in the comments
You can use a regular expression to check this:
var TheWordToCheck = "SomeWord";
var TheObject = {
"SomeProperty": "SomeWord 100"
};
var pattern = new RegExp(TheWordToCheck + ' \\d', 'g');
if (TheObject['SomeProperty'].match(pattern) != null) { ... }
Note that you have to do the backslashes twice in order to make sure that the first one is escaped in the pattern. You should also use the RegEx constructor in order to be able to use a variable in your pattern.

Remove all dots except the first one from a string

Given a string
'1.2.3.4.5'
I would like to get this output
'1.2345'
(In case there are no dots in the string, the string should be returned unchanged.)
I wrote this
function process( input ) {
var index = input.indexOf( '.' );
if ( index > -1 ) {
input = input.substr( 0, index + 1 ) +
input.slice( index ).replace( /\./g, '' );
}
return input;
}
Live demo: http://jsfiddle.net/EDTNK/1/
It works but I was hoping for a slightly more elegant solution...
There is a pretty short solution (assuming input is your string):
var output = input.split('.');
output = output.shift() + '.' + output.join('');
If input is "1.2.3.4", then output will be equal to "1.234".
See this jsfiddle for a proof. Of course you can enclose it in a function, if you find it necessary.
EDIT:
Taking into account your additional requirement (to not modify the output if there is no dot found), the solution could look like this:
var output = input.split('.');
output = output.shift() + (output.length ? '.' + output.join('') : '');
which will leave eg. "1234" (no dot found) unchanged. See this jsfiddle for updated code.
It would be a lot easier with reg exp if browsers supported look behinds.
One way with a regular expression:
function process( str ) {
return str.replace( /^([^.]*\.)(.*)$/, function ( a, b, c ) {
return b + c.replace( /\./g, '' );
});
}
You can try something like this:
str = str.replace(/\./,"#").replace(/\./g,"").replace(/#/,".");
But you have to be sure that the character # is not used in the string; or replace it accordingly.
Or this, without the above limitation:
str = str.replace(/^(.*?\.)(.*)$/, function($0, $1, $2) {
return $1 + $2.replace(/\./g,"");
});
You could also do something like this, i also don't know if this is "simpler", but it uses just indexOf, replace and substr.
var str = "7.8.9.2.3";
var strBak = str;
var firstDot = str.indexOf(".");
str = str.replace(/\./g,"");
str = str.substr(0,firstDot)+"."+str.substr(1,str.length-1);
document.write(str);
Shai.
Here is another approach:
function process(input) {
var n = 0;
return input.replace(/\./g, function() { return n++ > 0 ? '' : '.'; });
}
But one could say that this is based on side effects and therefore not really elegant.
This isn't necessarily more elegant, but it's another way to skin the cat:
var process = function (input) {
var output = input;
if (typeof input === 'string' && input !== '') {
input = input.split('.');
if (input.length > 1) {
output = [input.shift(), input.join('')].join('.');
}
}
return output;
};
Not sure what is supposed to happen if "." is the first character, I'd check for -1 in indexOf, also if you use substr once might as well use it twice.
if ( index != -1 ) {
input = input.substr( 0, index + 1 ) + input.substr(index + 1).replace( /\./g, '' );
}
var i = s.indexOf(".");
var result = s.substr(0, i+1) + s.substr(i+1).replace(/\./g, "");
Somewhat tricky. Works using the fact that indexOf returns -1 if the item is not found.
Trying to keep this as short and readable as possible, you can do the following:
JavaScript
var match = string.match(/^[^.]*\.|[^.]+/g);
string = match ? match.join('') : string;
Requires a second line of code, because if match() returns null, we'll get an exception trying to call join() on null. (Improvements welcome.)
Objective-J / Cappuccino (superset of JavaScript)
string = [string.match(/^[^.]*\.|[^.]+/g) componentsJoinedByString:''] || string;
Can do it in a single line, because its selectors (such as componentsJoinedByString:) simply return null when sent to a null value, rather than throwing an exception.
As for the regular expression, I'm matching all substrings consisting of either (a) the start of the string + any potential number of non-dot characters + a dot, or (b) any existing number of non-dot characters. When we join all matches back together, we have essentially removed any dot except the first.
var input = '14.1.2';
reversed = input.split("").reverse().join("");
reversed = reversed.replace(\.(?=.*\.), '' );
input = reversed.split("").reverse().join("");
Based on #Tadek's answer above. This function takes other locales into consideration.
For example, some locales will use a comma for the decimal separator and a period for the thousand separator (e.g. -451.161,432e-12).
First we convert anything other than 1) numbers; 2) negative sign; 3) exponent sign into a period ("-451.161.432e-12").
Next we split by period (["-451", "161", "432e-12"]) and pop out the right-most value ("432e-12"), then join with the rest ("-451161.432e-12")
(Note that I'm tossing out the thousand separators, but those could easily be added in the join step (.join(','))
var ensureDecimalSeparatorIsPeriod = function (value) {
var numericString = value.toString();
var splitByDecimal = numericString.replace(/[^\d.e-]/g, '.').split('.');
if (splitByDecimal.length < 2) {
return numericString;
}
var rightOfDecimalPlace = splitByDecimal.pop();
return splitByDecimal.join('') + '.' + rightOfDecimalPlace;
};
let str = "12.1223....1322311..";
let finStr = str.replace(/(\d*.)(.*)/, '$1') + str.replace(/(\d*.)(.*)/, '$2').replace(/\./g,'');
console.log(finStr)
const [integer, ...decimals] = '233.423.3.32.23.244.14...23'.split('.');
const result = [integer, decimals.join('')].join('.')
Same solution offered but using the spread operator.
It's a matter of opinion but I think it improves readability.

Categories

Resources