Is my JavaScript statement correct or not? [closed] - javascript

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I need to know my JavaScript sentence is correct or not? I am very much confused with the single quotes and plus symbols.
document.f.SQL.value ='\('+
document.f.SQL.value + a[i] +
' >= \''+ document.f[a[i]+"_A"].value +
'\' AND '+ a[i] +' <= \''+
document.f[a[i]+"_B"].value +
'\) or DATEADD'+'\('+
'dd, 0, DATEDIFF'+'\('+
'dd, 0,'+ a[i] +'\)) = \''+
document.f[a[i]].value +
'\'';

I pasted your code in Closure Compiler and used the which gave no errors, so the syntax is correct. The generated code is:
document.f.SQL.value = "(" + document.f.SQL.value + a[i] + " >= '" + document.f[a[i] + "_A"].value + "' AND " + a[i] + " <= '" + document.f[a[i] + "_B"].value + ") or DATEADD" + "(" + "dd, 0, DATEDIFF" + "(" + "dd, 0," + a[i] + ")) = '" + document.f[a[i]].value + "'";
The options I used for this:
Optimization: Whitespace only
Formatting: Pretty print
Try to avoid such complex lines. Make use of variables. The same result could be achieved with the below:
var old = document.f.SQL.value + a[i];
var sql_a = document.f[ a[i] + "_A" ].value;
var sql_b = document.f[ a[i] + "_B" ].value;
var whatever = document.f[ a[i] ].value;
// (old) >= 'sql_a' AND
var sql = "(" + old + ") >= '" + sql_a + "' AND ";
// A <= 'sql_b')
sql += a[i] + " <= '" + sql_b + "') "
// or DATEADD(dd, 0, DATEDIFF(dd, 0, A)) = 'whatever'
sql += "or DATEADD(dd, 0, DATEDIFF(dd, 0, " + a[i] + ")) = '" + whatever + "';
document.f.SQL.value = sql;
The point is, try to split the string in smaller parts. I did not split the queries in smaller parts above, that's up to you.

If you need single quotes in your string and no double quotes (inside it) then use double quotes to delimit your string and you won't need to escape your single quotes.
I usually prefer single quotes to delimit strings in JavaScript especially when I tend to be working on HTML strings because I prefer double quotes for attributes. You can use either the single quote or double quote though, there's no functional difference like there is in PHP or other languages.
Your expression is quite difficult to read. Consider simplifying it, putting it into several instructions or finding/writing a reusable token substitution routine of some sort.
The escaping of brackets \( looks unnecessary, and concatenating two string literals too ' + '.
Expressions like document.f[a[i]+"_A"].value would be easier to read if they were assigned to meaningfully named variables before you used them.

Related

How to freeze text from moving in console.log

So I have a simple console.log script that prints this
Now when I add a letter is moves
any way to freeze it please?
code
It would probably make more sense to make all of your cells contain a space character if they are "empty". Take a look here:
var Cell_1 = "a";
var Cell_2 = " ";
var Cell_3 = " ";
var Cell_4 = " ";
var Cell_5 = " ";
var Cell_6 = " ";
var Cell_7 = " ";
var Cell_8 = " ";
var Cell_9 = " ";
console.log(
Cell_1 + "|" + Cell_2 + "|" + Cell_3 + "\n" +
Cell_5 + "|" + Cell_6 + "|" + Cell_6 + "\n" +
Cell_7 + "|" + Cell_8 + "|" + Cell_9 + "\n" +
)
This way all of your variables are the same width - one character.
For future reference, here's some code that would probably look a bit nicer:
// This is called a 2d array: essentially an array containing other arrays.
// Its good for storing grids or tables of information.
var cells = [
['a', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']
]
// This uses Array.reduce() to generate the string.
// Google it once you feel more confident :)
console.log(
cells.reduce(
(totalString, currentRow) => totalString + currentRow.join('|') + '\n',
''
)
)
The question isn't very clear but I am assuming that you want to keep a grid aligned, the grid having multiple cells that can contain a character or not.
The problem is that the empty cells are initialised to "" (empty string) which is of size 0, but when a character is set the size will be 1, so it will shift all the following cells of 1.
An easy solution is to use a " " (space) for the empty cell instead of a "". As a result the size of a cell will always be 1 and the whole grid won't be shifted.

DRY programming with JavaScript Mad Libs Challenge

I am new to programming.
I know that I could use functions and loops to keep from repeating this code, but I need help. Anyone?
var questions = 3;
var questionsCount = ' [' + questions + ' questions left]';
var adjective = prompt('Please type an adjective' + questionsCount);
questions -= 1;
questionsCount = ' [' + questions + ' questions left]';
var verb = prompt('Please type a verb' + questionsCount);
questions -= 1;
questionsCount = ' [' + questions + ' questions left]';
var noun = prompt('Please type a noun' + questionsCount);
alert('All done. Ready for the message?');
var sentence = "There once was a " + adjective;
sentence += ' programmer who wanted to use JavaScript to ' + verb;
sentence += ' the ' + noun + '.';
document.write(sentence);
I'd use a string template which contains, eg, {{noun}} to be replaced with a noun, which uses a regular expression to prompt the user for replacements to make:
const template = 'There once was a {{adjective}} programmer who wanted to use JavaScript to {{verb}} the {{noun}}.';
let questions = 3;
const result = template.replace(
/{{(.*?)}}/g,
(_, typeOfSpeechNeeded) => prompt(`Please type a ${typeOfSpeechNeeded}, ${questions--} question(s) left`)
);
console.log(result);
The regular expression
{{(.*?)}}
matches {{, followed by some characters, followed by }}, where those characters are put into a capturing group - this allows the .replace to examine the capturing group to determine what typeOfSpeechNeeded to display in the prompt.
The /g in the regular expression makes it global, which replaces all matches, not just the first match.
The backtick string is just a more readable way of interpolating strings:
prompt(`Please type a ${typeOfSpeechNeeded}, ${questions--} question(s) left`)
is equivalent to
prompt('Please type a ' + typeOfSpeechNeeded + ', ' + questions-- + ' question(s) left')

How to find hyphenated Strings

I search for specific words in a text and find them too. However, if the word I am looking for is divided into two lines by a hyphenation, the word will not be found. Here is a sample code.
searchString = "Hollywood";
newString = "";
text = "In India Hollywood is called Bollywood.";
var i = 0;
i = text.indexOf(searchString, i);
newString += text.substring(0, i) + " <<here begins my searchString>> " + text.substr(i, searchString.length) + " <<here ends my searchString>> " +
text.substring(i + searchString.length);
console.log(newString);
If the searchString Hollywood looks like
Holly-<br>wood
it will not be found.
How can I solve this problem in my Javascript code?
There are a few ways you could do it, but one of them would be to get rid of the - altogether if they're present:
searchString = "Hollywood";
newString = "";
text = "In India Holly-<br>wood is called Bollywood.";
filteredText = text.replace(/-<br>/,'');
var i = 0;
i = filteredText.indexOf(searchString, i);
newString += filteredText.substring(0, i) + " <<here begins my searchString>> " + filteredText.substr(i, searchString.length) + " <<here ends my searchString>> " +
filteredText.substring(i + searchString.length);
console.log(newString);
In this case, we just replace the -<br> characters with an empty string. It might not be the best approach, but refining it would depend on the context in which you intend to use it.
I hope that the regex and replace idea can help you customize a solution that best fit your needs.

Javascript regex replace yields unexpected result

I have this strange issue, hope that someone will explain what is going on.
My intention is to capture the textual part (a-z, hyphen, underscore) and append the numeric values of id and v to it, underscore separated.
My code:
var str_1 = 'foo1_2';
var str_2 = 'foo-bar1_2';
var str_3 = 'foo_baz1_2';
var id = 3;
var v = 2;
str_1 = str_1.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
str_2 = str_2.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
str_3 = str_3.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
$('#test').html(str_1 + '<br>' + str_2 + '<br>' + str_3 + '<br>');
Expected result:
foo3_2
foo-bar3_2
foo_baz3_2
Actual Result:
foo3_2_2
foo-bar3_2_2
foo_baz3_2_2
Any ideas?
JS Fiddle example
Your pattern:
/([a-z_-]+)\d+/
matches only "foo1" in "foo1_2", and "foo" will be the value of the captured group. The .replace() function replaces the portion of the source string that was actually matched, leaving the remainder alone. Thus "foo1" is replaced by "foo3_2", but the original trailing "_2" is still there as well.
If you want to alter the entire string, then your regular expression will have to account for everything in the source strings.
Just try with:
str_1 = str_1.match(/([a-z_-]+)\d+/)[1] + id + '_' + v;
Use this instead to capture 1_2 completely:
str_1 = str_1.replace(/([a-z_-]+)\d+_\d+/,'$1' + id + '_' + v);
Because you want to replace _2 also of string. Solution can be this:
str_1 = str_1.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
str_2 = str_2.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
str_3 = str_3.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
DEMO
Your pattern actually includes the first digits, but it will store only the textual part into $1:
foo1_2
([a-z_-]+)\d+ = foo1
$1 = foo
The pattern stops searching at the first digits of the string.
if you want to replace any characters after the textual part, you could use this pattern:
/([a-z_-]+)\d+.*/

Prepend a number with $ in javascript

I have a small script ( using nouislider )
I wish to prepend the rangeThing values with $ sign as we are outputting prices.
Code I have is:
$("#slider").noUiSlider({
range: [0, 1000000]
,start: [350000, 700000]
,handles: 2
,step: 50000
,slide: function(){
var values = $(this).val();
$("span.rangeThing").text(
values[0] +
" - " +
values[1]
);
}
,serialization: {
to: [$("#exTO"),$("#exFR")]
,resolution: 1
}
});
The javascript creates a span like <span class="rangeThing"></span>
The output format is like this 200000 - 350000
I would like to format with ( commas ) as thousand separators, but thats gonna get messy. So I am trying to prepend the 2 sets of values with $ sign to signify a price.
So resultant output is like $200000 - $350000
I tried changing the values to something like this, but that didnt work lol.
$("span.rangeThing").text(
+ "$" + values[0] +
" - " +
+ "$" + values[1]
);
I am not sure if I am on the right track, and that the fact I am trying to echo $ could be the culprit, and perhaps I should use unicode, either way it isnt working.
Help appreciated
The problem is that the unary plus in Javascript implcitly converts the operand to a number. This means that
+ "$"
actually evaluates to NaN.
Just place the + operator only between terms and things should go as you expect.
Do it in one line to see what's going on:
You are starting with a +
The third line has double +
One line would be easier to read:
$("span.rangeThing").text("$" + values[0] + " - $" + values[1]);
Well, in your example there appears to be an extra + operator in the example you gave. As you see in the example you gave:
$("span.rangeThing").text(
values[0] +
" - " +
values[1]
);
This will result in the string "1 - 2", assuming values = [1, 2]. You should be able to simple add on the $ by doing something like:
$("span.rangeThing").text(
"$" + values[0] +
" - " +
"$" + values[1]
);
As you've probably realized, the example you posted has some syntactic errors -- you have +'s everywhere! One thing to be aware of -- if you are trying to combine strings in the same line as numeric operations, you will need additional parentheses. So, if you had:
var string = "foo"+2+3+"bar";
your string would be:
foo23bar
whereas if you had:
var string = "foo"+(2+3)+"bar";
your string would be:
foo5bar
In addition, here's how you can add the commas if you want...
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
To use it, just add the function to your file, and use it like this...
$("span.rangeThing").text("$" + addCommas(values[0]) + " - " + "$" + addCommas(values[1]));

Categories

Resources