Replacing comma by plus in javascript for entire project - javascript

I use winston to perform logging currently and have written a common method for it to be used all over project. Problem is, many of logging statements are like, logger.info("here is the data" , data)
With comma as concatenator, i couldn't log data in console. data can also be a content containing comma so I wouldn't be able to just use replace ',' by '+' .
My idea is regex can be like, if text starts with ' or " and its next character is ',' at end of quotes, replace with '+'
Ain't sure if it would be right but still, please help with your suggestions.

Perhaps you can monkey-patch it with something like
logger.info = ((infoFunc) => {
// create the patched info that concatenates all arguments
// before calling the original logger.info
let patch = () => {
// put any logic here that you need to achieve the desired result.
var message = args.join('');
infoFunc(message);
};
return patch;
})(logger.info);
Not tested
Just make sure it's run right after the logger is set up.
This will work as a quick fix to get things running but I wouldn't recommend leaving it in your code and should be removed once all calls to logger.info have been cleaned up.

Related

nodeJS for each new line in a variable, add a hyphen?

I have a single string variable that when logged to console looks like the following with line breaks:
index
project.json
extras
I would like to be able to print it like:
-index
-project.json
-extras
what would be a good way to start on this? I am still in the process of learning JS, so I really have nothing to show for what I've tried, sorry.
I have tried some of the methods(console.log('-' + files_var)), but this does:
that does this:
- index
project.json
extras
You can replace all the line breaks with a line break and a - using .replace() passing a regex /...regex.../ and giving it a global so it replaces all instances. Remember the first string would not have a line break so we will need to add it manually.
console.log("-" + files_var.replace(/\n\r/g, '\n\r -'))
DEMO

SyntaxError: identifier starts immediately after numeric literal?

I have been working on my project where I had to do some updates on my data records. After I finished my update I got an error: SyntaxError: identifier starts immediately after numeric literal and this line of code was below that error in firebug : maxScores.ew-19a = ''
I looked up in my code and I found where is this output coming from, here is the code:
var maxScores = new Object;
<cfoutput query="getRec">maxScores.#LCase(tCode)# = '#maxScore#';</cfoutput>
In my update I had to put - symbol between letter and number, in old data I did not have that so I think that causing the problem here. I was wondering how I can prevent this or if there is any method that I have to put around my output to prevent this? If you know how this can be fixed pleas let me know. Thank you.
ColdFusion will attempt to subtract ew from 19a when you just dump it between to pound signs like that. You will need to use bracket/object notation here. Try this:
<cfoutput query="getRec">
maxScores.#LCase(getRec["tCode"][currentrow])# = '#getRec["maxScore"][currentrow]#';
</cfoutput>
If you want to Lower case something do it in the query. Outputing JS using CF is useful and solves many problems, but you want to keep it as clean as possible to keep your brain from fogging over. :)

How to allow for another index string to run a script

I have no script abilitiy, but i'd like to edit an existing script which is currently restricting the script from running on any page other then the one that has a certain string in the URL.
Here is the snippet of the script which limits it from running
if(location.href.indexOf("MODULE=MESSAGE")>0||location.href.indexOf("/message")>0)
This only allows the script to run on these pages
mysite/2014/home/11609?MODULE=MESSAGE1
and the pages range from Message1 to Message20
mysite/2014/home/11609?MODULE=MESSAGE20
I would like to also allow the script to be loaded and ran on these pages
mysite/2014/options?L=11609&O=247&SEQNO=1&PRINTER=1
where the SEQNO=1 ranges from 1 to SEQNO=20, just like the MESSAGE1-MESSAGE20 do
Can someone show me how i can edit that small snippet of script to allow the SEQNO string found in the url to work also.
Thanks
If you can't just remove the condition altogether (there's not enough context to know if that's an option), you can just add another or condition (||) like so:
if(location.href.indexOf("MODULE=MESSAGE")>0
||location.href.indexOf("/message")>0
||location.href.indexOf("SEQNO=")>0)
Note that the second clause there isn't actually being used in any of your examples, so could potentially be removed. Also note that this isn't actually checking for a number so it isn't restricted to Message1 to Message20 as you suggest. It would match Message21 or even MessageFoo. That may or may not be a problem for you. You can make the conditions as restrictive or as lose as makes sense.
If you just want to check for the existence of "SEQNO", simply duplicate what is being done for "MODULE_MESSAGE".
if(location.href.indexOf("MODULE=MESSAGE")>0 ||
location.href.indexOf("SEQNO=")>0 ||
location.href.indexOf("/message")>0)
If you want to also ensure that "MESSAGE" ends in 1-20, and "SEQNO=" ends in 1-20, you can use a regex.
// create the end part of the regex, which checks for numbers 1-20
var regexEnd = "([1-9]|1[0-9]|20)[^0-9]*$";
// create the individual regexes
var messageRegex = new RegExp("MODULE=MESSAGE" + regexEnd);
var seqnoRegex = new RegExp("SEQNO=" + regexEnd);
// now comes your if statement, using the regex test() function, which returns true if it matches
if(messageRegex.test(location.href) ||
seqnoRegex.test(location.href) ||
location.href.indexOf("/message")>0)

My regex works in online editor but in FireBug it makes the browser to crash

I have written the following regex to catch anything within two parenthesis of a text:
var rule = /[a-zA-Z0-9]*(\(+[a-zA-Z\s0-9]*\))*[a-zA-Z0-9\s]/;
It works in this website: http://regex101.com/ (javascript section)
Look the right side of the window and you see the bottom section shows the matched string which is what I want.
But in firebug when I execute the following code it crashes. Why? how then should I catch the group in parenthesis?
var rule = /^[a-zA-Z0-9\s]*(\(+[a-zA-Z\s0-9]*\))*[a-zA-Z0-9\s\,]*/;
var str = "He left us (with anger), but came back all cool and modest.";
var res = "";
while((res = rule.exec(str)) !== null)
{
console.log("Good");
}
console.log(res);
Or maybe I'm totally wrong and am missing something?
"But in firebug when I execute the following code it crashes. Why?"
To use .exec() in a loop like that, the regex must be global. Otherwise it's just going to keep getting the first match, resulting in an infinite loop.
// make it global ------------------------------------------------v
var rule = /^[a-zA-Z0-9\s]*(\(+[a-zA-Z\s0-9]*\))*[a-zA-Z0-9\s\,]*/g;
When global, the regex object becomes stateful, and each subsequent .exec() will begin from the character after the last match.
When there are finally no matches left, it'll return null, breaking the loop.
As others pointed out in the comments, the leading ^ will guarantee only one match (without the m modifier anyway), so you'll probably want to remove that. It's not the cause of the crash though.

Parsing a string returned from ckeditor using javascript string methods

I am trying to get a certain area of data out from ckeditor. In order to do that I use the following code
function get_body_html(){
var email = CKEDITOR.instances['message'].getData();
var before_body = header_to + to + to_subject + subject + subject_body;
var s_index = email.indexOf(before_body)+before_body.length;
var e_index = email.indexOf(body_footer);
return email.substring(s_index,e_index);
}
For some reason that works when I do this on page load
CKEDITOR.instances.message.setData(header_to + to + to_subject+
subject + subject_body + body_text + body_footer);
get_body_html();
it works correctly and gives me the same string that is contained in body_text.
But when I do this
body_text = get_body_html();
CKEDITOR.instances.message.setData(header_to + to + to_subject + subject +
subject_body + body_text + body_footer);
in an onclick function it gets the wrong indexs somehow. Sometimes it can't find the string and returns -1 other times it just gets a weird index that doesn't make sense. These index variations only happen when my code is changed to tackle the problem a different way. So if it is the wrong indices like -5 and 2 then those would continue to be the wrong indices until I made a code change.
There are two facts that you should know about editor.setData.
In some cases it is asynchronous (it depends on the type of editor). That's why it also accepts a callback. Therefore any code that is meant to be executed after setData() should be executed in that callback.
It never is asynchronous before editor is ready. In this period (between editor initialization and instanceReady event) it works in a different mode - it just caches the set value and on getData() it returns exactly that value.
So, as I see on page load you call synchronously setData() and getData() - your function works because you get the value you're expecting to get.
But then, when you try to getData() when editor is already ready you get the HTML parsed, fixed, processed and perhaps differently formatted by CKEditor. I guess that your indexOf() checks are not enough to handle this. You have to rethink your function - e.g. regexp can help.
What also can help is removing htmlwriter plugin, which formats HTML in a way which may make it harder for you to work with it. E.g.:
config.removePlugins = 'htmlwriter';
I was able to get it to work. So the htmlwriter was one of the problems because it must add spaces in between by HTML tags. The other issue I found is that it strips some of the semicolons out in some of the style attributes. Overall CKEditor does a lot of formatting of the source which makes it very hard to index correctly but it's pretty much a trial and error thing. I ended up using the search JavaScript method for strings which can take a regular expression but I used it the same way indexOf would be used so I don't really know if that made a difference or not.

Categories