RegExp in Node Js not working: Cannot call method 'toString' of null - regex

This exact function does not work on Node Js, even though it work fine on a regular browser. How can I make it work on NodeJS?
Example: http://jsfiddle.net/wC53N/
var MyHereDoc = function() {
var bodyEmail = function(){
var test = 1;
/*HEREDOC
<div>
Hola1
<p>
hola2
</p>
</div>
HEREDOC*/
};
var here = "HEREDOC";
var reobj = new RegExp("/\\*"+here+"\\n[\\s\\S]*?\\n"+here+"\\*/", "m");
str = reobj.exec(bodyEmail).toString();
str = str.replace(new RegExp("/\\*"+here+"\\n",'m'),'').toString();
toPrint = str.replace(new RegExp("\\n"+here+"\\*/",'m'),'').toString();
document.getElementById("demo").innerHTML = toPrint;
}
MyHereDoc();
If you try to run this same code on NodeJS u will get this error:
Cannot call method 'toString' of null
But Why? any idea how to make it works, or what am I doing wrong?
Thanks

Related

script.google.com error: TypeError: Cannot read property 'values' of undefined [duplicate]

This question already has answers here:
How can I test a trigger function in GAS?
(4 answers)
Closed 4 months ago.
I am trying to use a form submit to automatically complete a google doc template I have created. But I keep getting the error TypeError: Cannot read property 'values' of undefined, I am a complete newbie, can someone help me please?
function autoFillGoogleDocFromForm(e) {
//e.values is an array of form values
var timestamp = e.values[0];
var EmailAddress = e.values[1];
var CallReportWriter = e.values[2];
var DateOfMeeting = e.values[3];
var NameOfTheCustomerProspect = e.values[4];
var ContactNameFromClient = e.values[5];
var TitleandContacts = e.values[6];
var PresentfromSesomo = e.values[7];
var MeetingObjectives = e.values[8];
var MeetingResult = e.values[9];
var Background = e.values[10];
var Opportunities = e.values[11];
var Followuprequired = e.values[12];
var Responsible = e.values[13];
var Targetdates = e.values[14];
//file is the template file, and you get it by ID
var file = DriveApp.getFileById('12zJTxLgy_Nmxk1FScyZ3vqHzYnKQ55ckdQ8RsYy-MdA');
//We can make a copy of the template, name it, and optionally tell it what folder to live in
//file.makeCopy will return a Google Drive file object
var folder = DriveApp.getFolderById('1SorfCjOGknFVt1ch39MJ7atBorLf_Sdr')
var copy = file.makeCopy(DateOfMeeting + ',' + NameOfTheCustomer/Prospect, CallReport);
//Once we've got the new file created, we need to open it as a document by using its ID
var doc = DocumentApp.openById(copy.getId());
//Since everything we need to change is in the body, we need to get that
var body = doc.getBody();
//Then we call all of our replaceText methods
body.replaceText('{{MeetingDate}}', DateOfMeeting);
body.replaceText('{{NameOfCustomer}}', NameOfTheCustomer/Prospect);
body.replaceText('{{ReportWriterName}}', CallReportWriter);
body.replaceText('{{ContactNameFromClient}}', ContactNameFromClient);
body.replaceText('{{TitleAndContact}}', TitleandContacts);
body.replaceText('{{PresentFromSesomo}}', PresentfromSesomo);
body.replaceText('{{MeetingObjectives}}', MeetingObjectives);
body.replaceText('{{MeetingResults}}', MeetingResult);
body.replaceText('{{Background}}', Background);
body.replaceText('{{Opportunities}}', Opportunities);
body.replaceText('{{FollowUpRequired}}', Followuprequired);
body.replaceText('{{Responsible}}', Responsible);
body.replaceText('{{TargetDate}}', Targetdates);
//Lastly we save and close the document to persist our changes
doc.saveAndClose();
}
Open the script editor of the sheet where the form response is landing
//
function onFormSubmit(e) {
var resp = e.source.getActiveSheet().getRange(e.range.rowStart,1, e.range.rowStart,14 ).getValues();
var timestamp = resp[0][0];
var EmailAddress = resp[0][1];
var CallReportWriter = resp[0][2];
var DateOfMeeting = resp[0][3];
// continue your code - I have not tested it
}
In script editor, you have to install the on-form-submit trigger
Then as soon as form response lands, your code will run and do whatever you want.

How do I outdent by a specific amount of tabs?

I'm trying to create a function that I can use to outdent (versus indent) a specific amount.
Here is what I have so far. This removes all tabs at the beginning of the lines. I think I need to create a dynamic pattern or use a function but I'm stuck:
var outdentPattern:RegExp = /([\t ]*)(.+)$/gm;
function outdent(input:String, outdentAmount:String = "\t"):String {
var outdentedText:String = input.replace(outdentPattern, outdentAmount + "$2");
return outdentedText;
}
Here is test data:
<s:BorderContainer>
<html:htmlOverride><![CDATA[
<script>
var test:Boolean = true;
test = "string";
</script>]]>
</html:htmlOverride>
</s:BorderContainer>
The test would be remove one tab, remove two tabs, etc.
Expected results at one tab would be:
<s:BorderContainer>
<html:htmlOverride><![CDATA[
<script>
var test:Boolean = true;
test = "string";
</script>]]>
</html:htmlOverride>
</s:BorderContainer>
And two tabs:
<s:BorderContainer>
<html:htmlOverride><![CDATA[
<script>
var test:Boolean = true;
test = "string";
</script>]]>
</html:htmlOverride>
</s:BorderContainer>
And three tabs with the inner tabs (whitespace) collapsing down:
<s:BorderContainer x="110" height="160" width="240" y="52">
<html:htmlOverride><![CDATA[
<script>
var test:Boolean = true;
</script>
]]></html:htmlOverride>
</s:BorderContainer>
Interesting note:
The editor on SO is outdenting when you click code button when the code is already indented.
You could either construct a RegExp object from a template, or you could use the regular expression several times:
var temp:String = '^[\t ]{0,';
function outdent(input:String, amount:Number = 1):String {
return input.replace(new RegExp(temp + amount.toString() + '}', 'gm'), '');
}
Or:
var pattern:RegExp = /^[\t ]/gm;
function outdent(input:String, amount:Number = 1):String {
for (var i:Number = 0; i < amount; i++)
input = input.replace(pattern, '');
return input;
}

ReactJS Simulate change value / unit testing

i try to simulate a test of a value change on my InputText component. I really don't know how to make that. I just know I must use the ref and the onChange method. But when I put a ref on my test I got an error like "you might be adding a ref to a component that was not created inside a component's render method".
Edit = I give a ref in the render of my InputText component
This is the render of my InputText component
render: function () {
console.log('passerender');
var attrs = this.generateAttributes();
var type = this.props.area ? "textarea" : "text";
return (
<Input
className={this.props.menuClassName}
type={type}
{...attrs}
{...this.props.evts}
className={this.props.menuClassName}
onChange = {this.handleChange}
onBlur = {this.handleBlur}
value={this.state.value}
ref = "InputField"
hasFeedback
/>
);
}
});
This is my test page of my InputText component:
var React = require('react'),
InputText = require('../resources/assets/js/testcomponents/InputText.js').InputTextEditable,
TestUtils = require('react-addons-test-utils'),
ReactDOM = require('react-dom');
describe('InputText', function () {
var InputElement = TestUtils.renderIntoDocument(
<InputText
area={false}
//evts={{onChange: handleChange}}
attributes={{
label:'Test Input Isole',
name:'InputTextArea',
value: '',
wrapperClassName: 'col-md-4',
labelClassName: 'col-md-2',
groupClassName: 'row'
}}
//ref="InputField"
editable={true}/>);
var DomElement = ReactDOM.findDOMNode(InputElement);
var inputV = ReactDOM.findDOMNode(InputElement.refs.InputField);
var input = DomElement.getElementsByTagName('input')[0];
var inputspan = DomElement.getElementsByTagName('span')[1];
it('updates input value on key press', function () {
inputV.value = 'test';
expect(input.getAttribute('value')).toEqual('');
TestUtils.Simulate.change(inputV);
TestUtils.Simulate.keyDown(inputV, {key: "Entrer", keyCode: 13, which: 13});
expect(input.getAttribute('value')).toEqual('test');
});
You can use findRenderedComponentWithType or findRenderedDOMComponentWithTag
You don't need to call findDOMNode explicitly, because TestUtils has done this for you.
var InputElement = TestUtils.renderIntoDocument(
<InputText {...yourProps}/>
);
// Assuming there is only one <input /> DOM element in your Input
var input = TestUtils.findRenderedComponentWithType(InputElement, Input)
// or you can just find <input /> directly
var input = TestUtils.findRenderedDOMComponentWithTag(InputElement, 'input');
TestUtils.Simulate.change(input);
TestUtils.Simulate.keyDown(input, {key: "Entrer", keyCode: 13, which: 13});
Ok I find the problem of the syntax error. It was on my html5validator on my input mixin. I put a try/catch to solve this :
var html5Validity = true;
if (DOM !== undefined) {
try {
html5Validity = $(DOM).find(':invalid').length == 0;
console.log('passe');
} catch (e) {
console.log('html5Validity = [catch]');
html5Validity = true;
}
}
attrs = _.extend({'data-valid': validation.isValid && html5Validity}, attrs);
Now it's OK ! Thank you ! :)

How do I return data to a template with Knockout and Requirejs modules?

I'm having a difficult time returning data from a module using RequireJS and Knockout to populate my markup for my single page app. Knockout can't seem to find my data binding observables.
I'm trying to keep each view in a separate js file, but I'm failing to identify where I've gone wrong. Here's what I have so far:
/app/app.js
define(function(require) {
require('simrou');
var $ = require('jQuery'),
ko = require('knockout'),
videoView = require('videoView');
var init = function() {
var viewModel = function() {
var self = this;
self.currentPage = ko.observable();
self.videoView = new videoView();
}
var view = new viewModel();
ko.applyBindings( view );
_router = new Simrou({
'/video/:id': [ view.videoView.getVideo ]
});
_router.start();
};
return {
init: init
};
});
/app/videoView.js
define(function(require) {
"use strict";
var $ = require('jQuery'),
ko = require('knockout');
return function() {
var self = this;
self.currentPage = ko.observable( 'showVideo' );
self.currentVideo = ko.observable();
self.videoData = ko.observableArray([]);
self.videoList = ko.observableArray([]);
var getVideo = function( event, params ) {
// ajax pseudo code
$.ajax({});
self.videoData( dataFromAjaxCall );
}
return {
getVideo: getVideo
};
};
});
index.html
When I browse to /#/video/14 I receive the following error:
Uncaught ReferenceError: Unable to parse bindings.
Bindings value: attr: { 'data-video-id': videoData().id }
Message: videoData is not defined
Here's the markup:
<section id="showVideo" data-bind="fadeVisible: currentPage()=='showVideo', with: $root">
<div class="video" data-bind="attr: { 'data-video-id': videoData().id }></div>
</section>
Like I said, I'm trying to keep each view separated, but I would love some enlightenment on what I'm doing wrong, or if this is even possible? Is there a better more efficient way?
videoData is a property of $root.videoView, not of the root model (the one you passed to applyBindings). It's also an observableArray, so videoData() is just a plain array and even if you get the context right, you won't be able to access its id property, since, being an array, it doesn't have.named properties.

XPath regex combined with preg_match

I have a simple but invisible (for me) error in code. Can you help me?
With this code in my php file:
$location = $xpath2->query("//script")->item(1)->textContent;
I got (select) this:
<script class="" type="text/javascript">
//<![CDATA[
var html = '';
var lat = 44.793530904744074;
var lang = 20.5364727973938;
if (GBrowserIsCompatible())
{
var map = new GMap2(document.getElementById("map_canvas"));
var ct = new GLatLng(lat, lang);
map.setCenter(ct, 15);
map.addControl( new GSmallMapControl() );
//map.addControl( new GHierarchicalMapTypeControl () );
var gm=new GMarker(ct);
if(html != '') {
GEvent.addListener(gm, "click", function() {
this.openInfoWindowHtml( html );
});
}
map.addOverlay(gm);
map.enableContinuousZoom();
map.enableInfoWindow();
}
//]]>
</script>
Then I try to fetch 'lat' and 'lang' with this code:
$location = $xpath2->query("//script")->item(1)->textContent;
preg_match('/var\s+lat\s+=\s+(\d+\.\d+)\s*;/', $location, $lat);
preg_match('/var\s+lang\s+=\s+(\d+\.\d+)\s*;/', $location, $lng);
$data['lat'] = $lat[1];
$data['lng'] = $lng[1];
But always show that lat and lang is 0, 0 when they should be 44.34534 and 20.5345.
PLEASE HELP! where you think that I'm wrong (my English is not very well, sorry for that)
Maybe something like below. Beware though you're trying to parse JavaScript.
preg_match('/(?:^|(?<=\s))var\s+lat \s* = \s* (?=[^;]*\d) ([+-]?\d*\.?\d*)\s*; /x', $location, $lat);
preg_match('/(?:^|(?<=\s))var\s+lang\s* = \s* (?=[^;]*\d) ([+-]?\d*\.?\d*)\s*; /x', $location, $lng);
Run sample: http://www.ideone.com/SEgVb
Or, just try to get more general information:
preg_match('/(?:^|(?<=\s))var\s+lat \s*=\s* ([^;]*) \s*; /x', ...
Try like this:
preg_match('/var\s+lat\s+=\s+([\d.-]+)/', $location, $lat);
preg_match('/var\s+lang\s+=\s+([\d.-]+)/', $location, $lng);
The [\d.-]+ matches any group with numbers . or - (lat/lon can be negative)