Error in Regex101 or my code? JavaScript / Node - javascript

I am currently doing an exercise that I got from my school. It's about regex but I am not sure if there is something wrong with my function or my regex code. We were told to use regex101.com to try things out.
in that site it looks like this and it all seems to work.
But in my file I get this.
Here is the code:
function isCheck(words) {
const check = /\Bche(ck|que)/;
return check.test('check', 'cheque');
}
So I am thinking that maybe there is something wrong in my function but I am not sure what that could be.
this is what its testing against
describe('The check-checker', () => {
it.only('should match check', () => {
const check = 'check';
assert.equal(matcher.isCheck(check), true);
});
it.only('should match cheque', () => {
const cheque = 'cheque';
assert.equal(matcher.isCheck(cheque), true);
});
Does anyone have any ideas?

I finally found it, for anyone else in a similar situation.
The function was wrong. I needed a parameter and to call on it in the function.
function isCheck(test) {
const check2 = /\b(check|cheque)\b/i;
if (check2.test(test)) {
return true;
}
return false;
}
module.exports.isCheck = isCheck;
There is the code.

Related

Check string contains JavaScript code or normal string?

There is a situation to run code inside javascript string. But there is two possibilities that the string can contain a javascript or not. So I want to check first is there any javascript code before executing the string.
let code = "alert('Run Run')";
let runFunction = new Function(code);
runFunction();
I tried regex apporach, but it would not work.
let exists = code.match(/[!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/) ? "YES" : "NO";
Is there any way to check this.
You can check the syntax of the string to see if it can be parsed properly before running it for real, though this essentially just involves attempting to execute the string as Javascript anyway.
const stringIsJS = (str) => new Promise((resolve) => {
window.addEventListener('unhandledrejection', (errorEvent) => {
// Don't pollute the console with additional info:
errorEvent.preventDefault();
resolve(errorEvent.reason.message === 'No syntax problems');
}, { once: true });
Promise.resolve().then(() => {
eval('throw new Error("No syntax problems");' + str);
});
});
(async () => {
console.log(
await stringIsJS('hello hello'),
await stringIsJS('const foo = "bar";'),
);
})();
throw new Error is inserted at the top of the code to be evaluated to ensure that the stringIsJS only checks the syntax of the string, rather than actually running any substantive code.
Or, using Acorn:
const stringIsJS = (str) => {
try {
acorn.Parser.parse(str);
return true;
} catch(e){
return false;
}
};
console.log(
stringIsJS('hello hello'),
stringIsJS('const foo = "bar";'),
);
<script src="https://cdn.jsdelivr.net/npm/acorn#6.1.1/dist/acorn.min.js"></script>
(still, this is a very weird thing to have to determine programmatically - it would be much better to, for example, save an additional flag in a database to indicate whether a particular string is Javascript or not)

Gulp- Make sure file has comments in the beginning

I have multiple javascript files in a folder and I want to make sure that every file has comment in the beginning (that will explain the summary of file).
/*
This file will......
*/
function test () {
....
}
So is this possible using gulp-contains or something else?
I think this would be enough just to make sure if start of a file is the comment initial characters (/*)
gulp.src('./file.js')
.pipe(map(function(file, callback) {
var startWithComment = file.contents.toString().replace(/\n|\r/g, "").trim().startsWith("/*");
if (startWithComment){
// DO YOUR CHORES
}
}))
Another approach is to split the initial text to make sure if it is a valid multi-line comment.
function startsWithValidMultiLineComment(str){
try{
return str.replace(/\n|\r/g, "").trim().split("/*")[1].split("*/")[1].length > 0
} catch (e){
return false;
}
}
Following this approach str.split("/*")[1].split("*/")[0] would be your comment text
By using the regex provided by #Sajjad in previous answer. I have managed to achieve my goal. I have used gulp-if and gulp-fail instead (I find it more flexible).
Here is how I do that:
var condition = function (file) {
sFile = require('path').parse(file.path).name;
var startWithComment = file.contents.toString().replace(/\n|\r/g, "").trim().startsWith("/*");
return (!startWithComment);
}
gulp.task('taskName',
function() {
gulp.src('files/*.js')
.pipe(gulpIf(condition, fail(function () {
var message = 'Some message';
return message;
})));
});

How to fix jslint error 'Don't make functions within a loop.' while using find function inside loop

I am working to resolve all JSLint errors in my JS files.
Currently it shows 'Don't make functions within a loop.'on below sample code.
While(condition)
{
const userObj = find(users, user => user.id === currUserid);
}
currUserid is user id.
users is array of user.
I have tried to create separate function and pass it like below.
userChk = (user, id) => {
if (user.id === id) {
return user;
}
}
While(condition)
{
const userObj = find(users, userChk(currUserid));
}
But error shows like 'currUserid is not a function'. It will work fine if i do not pass currUserid value. But i can not check for different user ids. Please help me to find a better solution for this scenario. Thanks in advance.
Try this:
function findUser(users, currUserid) {
return find(users, user => user.id === currUserid)
}
while(condition) {
const userObj = findUser(users, currUserid);
}

how can I get the current url using protractor?

I am testing a website using protractor, and jasmine. I would like to know the current url in order to verify a test.
I have tried
function waitForUrlToChangeTo(urlRegex) {
var currentUrl;
return browser.getCurrentUrl().then(function storeCurrentUrl(url) {
currentUrl = url;
}
).then(function waitForUrlToChangeTo() {
return browser.wait(function waitForUrlToChangeTo() {
return browser.getCurrentUrl().then(function compareCurrentUrl(url) {
return urlRegex.test(url);
});
});
}
);
}
and I am using this function in this way
it('should log', function() {
//element(by.model('user.username')).sendKeys('asd');
//element(by.model('user.password')).sendKeys('asd');
element(by.linkText('Acceder')).click();
waitForUrlToChangeTo("http://localhost:9000/#/solicitudes");
});
If you want to just check the current URL, then use browser.getCurrentUrl():
expect(browser.getCurrentUrl()).toEqual("expectedUrl");
But, if you need to wait until URL matches a certain value, see the next part of the answer.
Here is a working code based on the example provided by the author of the Expected Conditions:
var urlChanged = function(url) {
return function () {
return browser.getCurrentUrl().then(function(actualUrl) {
return url != actualUrl;
});
};
};
Usage:
element(by.linkText('Acceder')).click();
browser.wait(urlChanged("http://localhost:9000/#/solicitudes"), 5000);
Alecxe your answer was very helpful.
But couldn't you just code:
expect(browser.getCurrentUrl()).toEqual('whateverbrowseryouarexpectingtobein');
And if this fails, then you know you're going to the wrong place.
Since Protractor 4.0.0 you can now use expected conditions to know when your url changed.
const EC = protractor.ExpectedConditions;
browser.wait(EC.urlContains('my-url'), 5000);
The asnwer I found comes from this one, I have no real credits for it. But just in case it help.
Protractor- Generic wait for URL to change

How can I change the way a lodash function is used for Typescript?

I have this code:
_.remove(this.home.modal.data.roles, function (currentObject) {
return currentObject.name === roleToDelete;
});
Can someone tell me how I can change the function call to the way it's usually done with Typescript. Also it gives me an error:
Message 118 TsLint: expected callSignature to have a typedef.
Any suggestions would be appreciated.
Is this what you're looking for:
_.remove(this.home.modal.data.roles, (currentObject) => {
return currentObject.name === roleToDelete;
});
You can also type your "currentObject" like this:
_.remove(this.home.modal.data.roles, (currentObject: Role) => {
return currentObject.name === roleToDelete;
});

Categories