How to freeze text from moving in console.log - javascript

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.

Related

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.

How to identify the following code patterns

I have a pattern of js promises that I want to identify for several keywords
For example if I put code like:
var deferred = Q.defer();
And in the file I have also the following respective value
deferred.reject(err);
deferred.resolve();
return deferred.promise;
The complete code
EXAMPLE 1
function writeError(errMessage) {
var deferred = Q.defer();
fs.writeFile("errors.log", errMessage, function (err) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve();
}
});
return deferred.promise;
}
And I want that if I put large code file (as string) to find that
this file contain the pattern
Another example
var d = Q.defer(); /* or $q.defer */
And in the file you have also the following respective value
d.resolve(val);
d.reject(err);
return d.promise;
Complete EXAMPLE 2
function getStuffDone(param) {
var d = Q.defer(); /* or $q.defer */
Promise(function(resolve, reject) {
// or = new $.Deferred() etc.
myPromiseFn(param+1)
.then(function(val) { /* or .done */
d.resolve(val);
}).catch(function(err) { /* .fail */
d.reject(err);
});
return d.promise; /* or promise() */
}
There is open sources which can be used to do such analysis(provide a pattern and it will found...)
There is some more complex patters with childProcess but for now this is OK
:)
The following regular expression may look a bit scary but has been built from simple concepts and allows a little more leeway than you mentioned - e.g. extra whitespace, different variable names, omission of var etc. Seems to work for both examples - please see if it meets your needs.
([^\s\r\n]+)\s*=\s*(?:Q|\$q)\.defer\s*\(\s*\)\s*;(?:\r?\n|.)*(?:\s|\r?\n)(?:\1\.reject\(\w+\)\s*;(?:\r?\n|.)*(?:\s|\r?\n)\1\.resolve\(\s*\w*\)\s*;|\1\.resolve\(\s*\w*\)\s*;(?:\r?\n|.)*(?:\s|\r?\n)\1\.reject\(\w+\)\s*;)(?:\r?\n|.)*(?:\s|\r?\n)return\s+(?:\1\.)?promise\s*;
Debuggex Demo
UPDATE: I made one correction to the code, i.e. changed set[2] to set[set.length - 1] to accommodate query sets of any size. I then applied the exact same algorithm to your two examples.
The solution I provide follows some rules that I think are reasonable for the type of search you are proposing. Assume you are looking for four lines, ABCD (case insensitive, so it will find ABCD or abcd or aBcD):
Multiple match sets can be found in a single file, i.e. it will find two sets in ABCDabcd.
Regex's are used for individual lines, meaning that variations can be included. (As only one consequence of this, it won't matter if you have a comment at the end of a matching line in your code.)
The patterns sought must always be on different lines, e.g. A and B can't be on the same line.
The matched set must be complete, e.g. it will not find ABC or ABD.
The matched set must be uninterrupted, i.e. it will not find anything in ABCaD. (Importantly, this also means that is will not find anything in overlapping sets, e.g. ABCaDbcd. You could argue that this is too limiting. However, in this example, which should be found, ABCD or abcd? The answer is arbitrary, and arbitrariness is difficult to code. Moreover, based on the examples you showed, such overlapping would not typically be expected, so this edge case seems unlikely, making this limitation reasonable.)
The matched set must be internally non-repeating, e.g. it will not find ABbCD. However, with AaBCD, it will find a set, i.e. it will find aBCD.
Embedded sets are allowed, but only the internal one will be found, e.g. with ABabcdCD, only abcd will be found.
The code snippet below shows an example search. It does not demonstrate all of the edge cases. However, it does show the overall functionality.
var queryRegexStrs = [
"I( really)? (like|adore) strawberry",
"I( really)? (like|adore) chocolate",
"I( really)? (like|adore) vanilla"
];
var codeStr =
"....\n" +
"Most people would say 'I like vanilla'\n" +
"....\n" +
"....\n" +
"....\n" +
"....\n" +
"Amir's taste profile:\n" +
"....\n" +
"I like strawberry\n" +
"....\n" +
"....\n" +
"I told Billy that I really adore chocolate a lot\n" +
"....\n" +
"I like vanilla most of the time\n" +
"....\n" +
"Let me emphasize that I like strawberry\n" +
"....\n" +
"....\n" +
"....\n" +
"....\n" +
"Juanita's taste profile:\n" +
"....\n" +
"I really adore strawberry\n" +
"I like vanilla\n" +
"....\n" +
"....\n" +
"....\n" +
"....\n" +
"Rachel's taste profile:\n" +
"I adore strawberry\n" +
"....\n" +
"Sometimes I like chocolate, I guess\n" +
"....\n" +
"I adore vanilla\n" +
"....\n" +
"....\n" +
"....\n" +
"....\n" +
"";
// allow for different types of end-of-line characters or character sequences
var endOfLineStr = "\n";
var matchSets = search(queryRegexStrs, codeStr, endOfLineStr);
function search(queryRegexStrs, codeStr, endOfLineStr) {
// break the large code string into an array of line strings
var codeLines = codeStr.split(endOfLineStr);
// remember the number of lines being sought
var numQueryLines = queryRegexStrs.length;
// convert the input regex strings into actual regex's in a parallel array
var queryRegexs = queryRegexStrs.map(function(queryRegexStr) {
return new RegExp(queryRegexStr);
});
// search the array for each query line
// to find complete, uninterrupted, non-repeating sets of matches
// make an array to hold potentially multiple match sets from the same file
var matchSets = [];
// prepare to try finding the next match set
var currMatchSet;
// keep track of which query line number is currently being sought
var idxOfCurrQuery = 0;
// whenever looking for a match set is (re-)initialized,
// start looking again for the first query,
// and forget any previous individual query matches that have been found
var resetCurrQuery = function() {
idxOfCurrQuery = 0;
currMatchSet = [];
};
// check each line of code...
codeLines.forEach(function(codeLine, codeLineNum, codeLines) {
// ...against each query line
queryRegexs.forEach(function(regex, regexNum, regexs) {
// check if this line of code is a match with this query line
var matchFound = regex.test(codeLine);
// if so, remember which query line it matched
if (matchFound) {
// if this code line matches the first query line,
// then reset the current query and continue
if (regexNum === 0) {
resetCurrQuery();
}
// if this most recent individual match is the one expected next, proceed
if (regexNum === idxOfCurrQuery) {
// temporarily remember the line number of this most recent individual match
currMatchSet.push(codeLineNum);
// prepare to find the next query in the sequence
idxOfCurrQuery += 1;
// if a whole query set has just been found, then permanently remember
// the corresponding code line numbers, and reset the search
if (idxOfCurrQuery === numQueryLines) {
matchSets.push(currMatchSet);
resetCurrQuery();
}
// if this most recent match is NOT the one expected next in the sequence,
// then start over in terms of starting to look again for the first query
} else {
resetCurrQuery();
}
}
});
});
return matchSets;
}
// report the results
document.write("<b>The code lines being sought:</b>");
document.write("<pre>" + JSON.stringify(queryRegexStrs, null, 2) + "</pre>");
document.write("<b>The code being searched:</b>");
document.write(
"<pre><ol start='0'><li>" +
codeStr.replace(new RegExp("\n", "g"), "</li><li>") +
"</li></ol></pre>"
);
document.write("<b>The code line numbers of query 'hits', grouped by query set:</b>");
document.write("<pre>" + JSON.stringify(matchSets) + "</pre>");
document.write("<b>One possible formatted output:</b>");
var str = "<p>(Note that line numbers are 0-based...easily changed to 1-based if desired)</p>";
str += "<pre>";
matchSets.forEach(function(set, setNum, arr) {
str += "Matching code block #" + (setNum + 1) + ": lines " + set[0] + "-" + set[set.length - 1] + "<br />";
});
str += "</pre>";
document.write(str);
Here is the exact same algorithm, just using your original examples 1 and 2. Note a couple of things. First of all, anything that needs escaping in the regex strings actually needs double-escaping, e.g. in order to find a literal opening parenthesis you need to include "\\(" not just "\(". Also, the regex's perhaps seem a little complex. I have two comments about this. First: a lot of that is just finding the literal periods and parentheses. However, second, and importantly: the ability to use complex regex's is part of the power (read "flexibility") of this entire approach. e.g. The examples you provided required some alternation where, e.g., "a|b" means "find a OR b".
var queryRegexStrs = [
"var deferred = Q\\.defer\\(\\);",
"deferred\\.reject\\(err\\);",
"deferred\\.resolve\\(\\);",
"return deferred\\.promise;"
];
var codeStr =
'function writeError(errMessage) {' + "\n" +
' var deferred = Q.defer();' + "\n" +
' fs.writeFile("errors.log", errMessage, function (err) {' + "\n" +
' if (err) {' + "\n" +
' deferred.reject(err);' + "\n" +
' } else {' + "\n" +
' deferred.resolve();' + "\n" +
' }' + "\n" +
' });' + "\n" +
' return deferred.promise;' + "\n" +
'}' + "\n" +
'';
// allow for different types of end-of-line characters or character sequences
var endOfLineStr = "\n";
var matchSets = search(queryRegexStrs, codeStr, endOfLineStr);
function search(queryRegexStrs, codeStr, endOfLineStr) {
// break the large code string into an array of line strings
var codeLines = codeStr.split(endOfLineStr);
// remember the number of lines being sought
var numQueryLines = queryRegexStrs.length;
// convert the input regex strings into actual regex's in a parallel array
var queryRegexs = queryRegexStrs.map(function(queryRegexStr) {
return new RegExp(queryRegexStr);
});
// search the array for each query line
// to find complete, uninterrupted, non-repeating sets of matches
// make an array to hold potentially multiple match sets from the same file
var matchSets = [];
// prepare to try finding the next match set
var currMatchSet;
// keep track of which query line number is currently being sought
var idxOfCurrQuery = 0;
// whenever looking for a match set is (re-)initialized,
// start looking again for the first query,
// and forget any previous individual query matches that have been found
var resetCurrQuery = function() {
idxOfCurrQuery = 0;
currMatchSet = [];
};
// check each line of code...
codeLines.forEach(function(codeLine, codeLineNum, codeLines) {
// ...against each query line
queryRegexs.forEach(function(regex, regexNum, regexs) {
// check if this line of code is a match with this query line
var matchFound = regex.test(codeLine);
// if so, remember which query line it matched
if (matchFound) {
// if this code line matches the first query line,
// then reset the current query and continue
if (regexNum === 0) {
resetCurrQuery();
}
// if this most recent individual match is the one expected next, proceed
if (regexNum === idxOfCurrQuery) {
// temporarily remember the line number of this most recent individual match
currMatchSet.push(codeLineNum);
// prepare to find the next query in the sequence
idxOfCurrQuery += 1;
// if a whole query set has just been found, then permanently remember
// the corresponding code line numbers, and reset the search
if (idxOfCurrQuery === numQueryLines) {
matchSets.push(currMatchSet);
resetCurrQuery();
}
// if this most recent match is NOT the one expected next in the sequence,
// then start over in terms of starting to look again for the first query
} else {
resetCurrQuery();
}
}
});
});
return matchSets;
}
// report the results
document.write("<b>The code lines being sought:</b>");
document.write("<pre>" + JSON.stringify(queryRegexStrs, null, 2) + "</pre>");
document.write("<b>The code being searched:</b>");
document.write(
"<pre><ol start='0'><li>" +
codeStr.replace(new RegExp("\n", "g"), "</li><li>") +
"</li></ol></pre>"
);
document.write("<b>The code line numbers of query 'hits', grouped by query set:</b>");
document.write("<pre>" + JSON.stringify(matchSets) + "</pre>");
document.write("<b>One possible formatted output:</b>");
var str = "<p>(Note that line numbers are 0-based...easily changed to 1-based if desired)</p>";
str += "<pre>";
matchSets.forEach(function(set, setNum, arr) {
str += "Matching code block #" + (setNum + 1) + ": lines " + set[0] + "-" + set[set.length - 1] + "<br />";
});
str += "</pre>";
document.write(str);
Here is the exact same algorithm, just using your original example 2:
var queryRegexStrs = [
"var d = (Q\\.defer\\(\\)|\\$q\\.defer);",
"d\\.resolve\\(val\\);",
"d\\.reject\\(err\\);",
"return d\\.promise(\\(\\))?;"
];
var codeStr =
"...." + "\n" +
"...." + "\n" +
"...." + "\n" +
"function getStuffDone(param) {" + "\n" +
" var d = Q.defer();" + "\n" +
"" + "\n" +
" Promise(function(resolve, reject) {" + "\n" +
" // or = new $.Deferred() etc." + "\n" +
" myPromiseFn(param+1)" + "\n" +
" .then(function(val) { /* or .done */" + "\n" +
" d.resolve(val);" + "\n" +
" }).catch(function(err) { /* .fail */" + "\n" +
" d.reject(err);" + "\n" +
" });" + "\n" +
" return d.promise;" + "\n" +
"" + "\n" +
"}" + "\n" +
"...." + "\n" +
"...." + "\n" +
"...." + "\n" +
"function getStuffDone(param) {" + "\n" +
" var d = $q.defer;" + "\n" +
"" + "\n" +
" Promise(function(resolve, reject) {" + "\n" +
" // or = new $.Deferred() etc." + "\n" +
" myPromiseFn(param+1)" + "\n" +
" .then(function(val) { /* or .done */" + "\n" +
" d.resolve(val);" + "\n" +
" }).catch(function(err) { /* .fail */" + "\n" +
" d.reject(err);" + "\n" +
" });" + "\n" +
" return d.promise();" + "\n" +
"" + "\n" +
"}" + "\n" +
"...." + "\n" +
"...." + "\n" +
"...." + "\n" +
"";
// allow for different types of end-of-line characters or character sequences
var endOfLineStr = "\n";
var matchSets = search(queryRegexStrs, codeStr, endOfLineStr);
function search(queryRegexStrs, codeStr, endOfLineStr) {
// break the large code string into an array of line strings
var codeLines = codeStr.split(endOfLineStr);
// remember the number of lines being sought
var numQueryLines = queryRegexStrs.length;
// convert the input regex strings into actual regex's in a parallel array
var queryRegexs = queryRegexStrs.map(function(queryRegexStr) {
return new RegExp(queryRegexStr);
});
// search the array for each query line
// to find complete, uninterrupted, non-repeating sets of matches
// make an array to hold potentially multiple match sets from the same file
var matchSets = [];
// prepare to try finding the next match set
var currMatchSet;
// keep track of which query line number is currently being sought
var idxOfCurrQuery = 0;
// whenever looking for a match set is (re-)initialized,
// start looking again for the first query,
// and forget any previous individual query matches that have been found
var resetCurrQuery = function() {
idxOfCurrQuery = 0;
currMatchSet = [];
};
// check each line of code...
codeLines.forEach(function(codeLine, codeLineNum, codeLines) {
// ...against each query line
queryRegexs.forEach(function(regex, regexNum, regexs) {
// check if this line of code is a match with this query line
var matchFound = regex.test(codeLine);
// if so, remember which query line it matched
if (matchFound) {
// if this code line matches the first query line,
// then reset the current query and continue
if (regexNum === 0) {
resetCurrQuery();
}
// if this most recent individual match is the one expected next, proceed
if (regexNum === idxOfCurrQuery) {
// temporarily remember the line number of this most recent individual match
currMatchSet.push(codeLineNum);
// prepare to find the next query in the sequence
idxOfCurrQuery += 1;
// if a whole query set has just been found, then permanently remember
// the corresponding code line numbers, and reset the search
if (idxOfCurrQuery === numQueryLines) {
matchSets.push(currMatchSet);
resetCurrQuery();
}
// if this most recent match is NOT the one expected next in the sequence,
// then start over in terms of starting to look again for the first query
} else {
resetCurrQuery();
}
}
});
});
return matchSets;
}
// report the results
document.write("<b>The code lines being sought:</b>");
document.write("<pre>" + JSON.stringify(queryRegexStrs, null, 2) + "</pre>");
document.write("<b>The code being searched:</b>");
document.write(
"<pre><ol start='0'><li>" +
codeStr.replace(new RegExp("\n", "g"), "</li><li>") +
"</li></ol></pre>"
);
document.write("<b>The code line numbers of query 'hits', grouped by query set:</b>");
document.write("<pre>" + JSON.stringify(matchSets) + "</pre>");
document.write("<b>One possible formatted output:</b>");
var str = "<p>(Note that line numbers are 0-based...easily changed to 1-based if desired)</p>";
str += "<pre>";
matchSets.forEach(function(set, setNum, arr) {
str += "Matching code block #" + (setNum + 1) + ": lines " + set[0] + "-" + set[set.length - 1] + "<br />";
});
str += "</pre>";
document.write(str);

Adding quotation mark in array values

I have an array of strings in object form received from file, only I need to add quotation mark around parameter names of objects which are strings inside an array and around their values between square brackets to convert those strings to proper objects.
["{Durdham Hall Electric: [e4.kwh]}", "{University Hall Substation: [e1.kwh]}",
"{University Hall Substation: [e2.kwh]}"]
I have no idea how to loop through values and to add required symbol in required part.
Maybe change
options.push('<option value="' + '{' + data[devices][1] + ': ' + '[' + 'e' + i + '.kwh' + ']' + '}' + '" >' + meterName + '</option>')
to something like this, then you get a little nice parsable JSON
var data = [[0, 'Durdham Hall Electric:']],
devices = 0,
meterName = 'meterName',
i = 3,
options = [];
options.push('<option value="' + '{ \\"device\\": \\"' + data[devices][1] + '\\", \\"kwh\\": \\"' + 'e' + i + '\\"}' + '">' + meterName + '</option>');
alert(options);
You can use Regex and forEach to do this:
var data = ["{Durdham Hall Electric: [e4.kwh]}", "{University Hall Substation: [e1.kwh]}",
"{University Hall Substation: [e2.kwh]}"];
data.forEach(function(v,i){
data[i] = JSON.parse( v.replace(/{(.+):\s\[(.*)\]}/g, '{"$1":["$2"]}') );
});
console.log(data); // Open your console to see the results
If the strings are always starting with a { you can use substring and then combine the string back together.
String part1;
String part2;
String result;
String str = "{Durdham Hall Electric: [e4.kwh]}"
Then use index of to find the :
part1 = str.subString(1, str.indexOf(":"));
part2 = str.subString(str.indexOf(":"), str.length());
result = "{\"" + part1 + "\"" + part2;
Believe something like this could work however you do have to make some assumptions. This is only for a single element so you would have a loop for each item in your string array.

How to create an array of variables from an array in Javascript

I have a variable called "information" which creates a multi-dimensional array. For each row in the array, I want to return a variable whose name is the first value in the array. In other words, given the 'information' array below, I'd want the following output:
var lunalovegood = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Luna Lovegood is a Ravenclaw!;
var dracomalfoy = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Draco Malfoy is a Slythering!;;
var hermionegranger = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Hermione Granger is a Gryffindor!;;
In other words, I want to be able to work with each of the elements in the 'information' array to create some markup. I already know how to get the information I need given the information array, but as you can see below I'd have to declare separate variables for each of the names.
for (var i = 0; i < information.length; i++) {
var htmlString = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Luna Lovegood is a Ravenclaw!
$('div').html(htmlString);
} //end for loop
var information = [
['lunalovegood', 'Ravenclaw', 'Luna', 'Lovegood', '(chaser)', 'lovegood.jpg', 4]
['dracomalfoy', 'Slytherin', 'Draco', 'Malfoy', '(seeker)', 'malfoy.jpg', 2],
['hermionegranger', 'Gryffindor', 'Hermione', 'Granger', '(none)', 'granger.jpg', 3],
];
The javascript below creates three variables called 'lunalovegood', 'dracomalfoy', and 'hermionegrange', but it's the long way of creating variables. How do I create these variables, one for each row in the array, by looping through the 0th indexed element in the 'information' array?
var myVariables = {}
,varNames = ["lunalovegood","dracomalfoy","hermionegranger"];
for (var i=0;i<varNames.length;i+=1){
myVariables[varNames[i]] = 0;
console.log(lunalovegood);
}
Your current approach just needs a most minor tweak to not require the second array.
var students = {}, i;
for (i = 0; i < information.length; ++i)
students[information[i][0]] = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i][1] + '!';
Now the key is set by taking the first item of the Array. You would then do the following for your text,
students['lunalovegood']; // "Luna Lovegood is a Ravenclaw!"
You're also missing a , in your information literal.
This should help you:
Every variable in the global scope can be accessed as a string property of the window object
var myvariable = 4;
alert(window["myvariable"]); // will alert 4
window["newvariable"] = 6;
alert(newvariable); // will alert 6
I agree with Bergi. Variables should represent a fixed finite set of members defined by code; data (as in the contents of a list) should generally not introduce new variables.
As such, here is the approach I would recommend (note that I've added a bit more than the "minimum required"; good luck!):
// Using a function makes it easy to change details and avoid leaking
// variables accidentally.
function loadWizards(information) {
var wizards = [];
for (var i = 0; i < information.length; i++) {
var info = information[i];
var name = info[0];
// Mapping to named properties means we can forget about indices!
wizards[name] = { // <- use Name to map to our Wizard object
house: info[1],
// ..
image: info[7]
};
}
return wizards;
}
// I have no idea if they are wizards, but give variables useful names.
// 'information' is too generic.
var wizards = loadWizards(information);
// Then later on, use it as:
alert("Hello " + wizards['hermionegranger'].name + "!")
// ^-- property access by Name
var formattedInfo = {};
$.each(information, function (i, v) {
formattedInfo[v[0]] = v[2] + ' ' + v[3] + ' is a ' + v[1];
});
there is a missing comma at the end of the 1st line of your definition of information.
BTW, I like Harry Potter very much.

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