I am working on an exercism. I am stuck on the first test that asks to match a regex to a new robot's name.
Here is the test ( I am only working on the one that doesn't have the x in front of it ).
var Robot = require('./robot-name');
describe("Robot", function() {
it("has a name", function() {
var robot = new Robot();
expect(robot.name).toMatch(/\w{2}\d{3}/);
});
xit("name is the same each time", function() {
var robot = new Robot();
expect(robot.name).toEqual(robot.name);
});
xit("different robots have different names", function() {
var robotOne = new Robot();
var robotTwo = new Robot();
expect(robotOne.name).not.toEqual(robotTwo.name);
});
xit("is able to reset the name", function() {
var robot = new Robot();
var originalName = robot.name;
robot.reset();
var newName = robot.name;
expect(originalName).not.toEqual(newName);
});
});
Here is my guess that isn't working.
var Robot = function(){
this.name = {};
Robot.prototype.new = function(robotNumber){
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 5;
var newName = Math.random().toString(36).slice(-5);
newName = MyRe.exec("/\w{2}\d{3}/");
newName.push(robotNumber);
this.name(newName);
};
};
module.exports = Robot;
Error message is on line 6 and responds:
Expected { } to match /\w{2}\d{3}/.
If anyone can point me in a direction of great resources for using prototypes and regex in javascript, it would be really helpful. Thank you.
In Your regex /\w{2}\d{3}/
\w{2} indicates word characters (a-z, A-Z, 0-9, _) (2 times) and
\d{3} indicates digits (0-9) (3 times)
And \w{2}\d{3} can be represented as,
And a matching example is : ab123
MyRe should be your regex such as /\w{2}\d{3}/g and .exec() should take in your string. You haven't defined MyRe. You could just write something like /\w{2}\d{3}/.exec(newName) if you wanted to be concise.
After trying to read your code it makes absolutely no sense. I can't even begin to imagine what your goal is.
Related
I am creating a calculator for my website and I am using the eval()
function, the issue is that I have a whitelist of allowed terms and
keys and I want to make sure only terms that are specifically in that
order are let through. For example, if I have a term called SQRT, I
would like terms that are only SQRT to be let through, right now I
have the problem that all instances of the letters in SQRT are also
let through, for example T
var input1 = "0";
var keywords = ["sqrt", "sin", "cos", "tan", "log","exp"];
function evalue(){
var keys = [];
keywords.forEach(element => {
keys.push("{^"+ element +"$}");
});
var whitelist = new RegExp("[^-()/1234567890*+." + keys.join() + "]", "g");
input1 = document.getElementById("calcInput1").value;
input1 = input1.replace(whitelist, '');
keywords.forEach(element => {
var elSearch = new RegExp(element, "g");
input1 = input1.replace(elSearch, "Math."+element)
});
input1 = eval(input1);
input1 = (Math.round((input1*100)))/100;
document.getElementById("calcResult").innerHTML=input1;
console.log(input1);
}
I thought that by separating the terms into {^$}, they would only find those specific terms and let them through.
[^xxxx] is not character inside, if you put there any word it will use characters from the word.
I would solve your problem with tokenizing the string using the keywords and numbers and filtering out what don't match:
var keywords = ["sqrt", "sin", "cos", "tan", "log","exp"];
var re = new RegExp('(' + keywords.join('|') + '|[0-9]+)');
var input = document.querySelector('input');
document.querySelector('button').addEventListener('click', function() {
var text = input.value.split(re).filter(Boolean).map(function(token) {
if (token.match(re)) {
return token;
}
return '';
}).join('');
console.log(text);
});
<input/>
<button>eval</button>
And suggestion if you want proper calculator you probably will need a parser, you can use some parser generator. I've wrote an article about different parser generators in JS (but it's in Polish), there are example codes and you can use google translate (link with translation). 5 parser generators in JavaScript (here is original post 5 Parserów i Generatorów Parserów w JavaScript use this link to check the example source code, because Google was converting the code into one line).
I need some help creating regexp. It's just I don't quite understand how to create a regexp. How do i create a validation for username with some rules like this
only Uppercase, lowercase, underscore(_) and dot(.) are allowed
start with an underscore(_)
I've already tried some regexp from mozilla developer site, but it doesn't seems right
var usernameRegex = new RegExp(/_+[A-Za-z]/);
var usernameRegexFound = usernameRegex.test(username.value);
if (!usernameRegexFound) {
msg = "Invalid Username";
}
I expect some username like so
_username = true
_username1 = false
.username = false
username = false
and also are there any sites for me to understand how to create regexp, because I got some more thing to do with it
function validuser(username) {
var msg = "valid";
var usernameRegex = new RegExp(/_+[A-Za-z]/);
var usernameRegexFound = usernameRegex.test(username);
if (!usernameRegexFound) {
msg = "Invalid Username";
}
return msg;
}
console.log(validuser("_username","Valid?"));
console.log(validuser("_username1","Invalid?"));
console.log(validuser(".username","Invalid?"));
console.log(validuser("username","Invalid?"));
When creating regex, you can help yourself using https://regex101.com/.
That said, here is your regex :
function test(username) {
const regex = new RegExp('^_{1}[A-Za-z\.]*$', 'i');
// Alternative version considering #thomas points
// const regex = new RegExp('^_[A-Za-z._]+$', 'i');
return regex.test(username);
}
console.log(test('test'));
console.log(test('_test'));
console.log(test('_te.s.t'));
console.log(test('_teST'));
console.log(test('Test_'));
console.log(test('^zdq^dz.'));
console.log(test('_teS/T'));
console.log(test('_9901A'));
I've this working RegExp in my JavaScript file:
var reA = new RegExp(urlValueToRemove);
var reB = new RegExp('(,&)');
var reC = new RegExp('(,,)');
var reD = new RegExp('(=,)');
var reE = new RegExp('(,$)');
window.history.pushState(null, null, decodeURIComponent(window.location.search).replace(reA, '').replace(reB, '&').replace(reC, ',').replace(reD, '=').replace(reE, ''));
Is it possible to concatenate / simplify this so that I don't need to do the replace 5 times?
I've asked this in the codereview community but there is nobody available so I think I must need to wait days there.
Example
When I have this URL here:
http://localhost.com/?color=Red,Blue,Green&size=X,L,M,S
When I want to remove now the Green from the URL I can pass Green to the first Regex reA and it gets removed from the URL:
http://localhost.com/?color=Red,Blue&size=X,L,M,S
You can use the capture group to indicate what should be kept, and join the two cases with a |: one case needs to keep the character that precedes the word (like =), the other what follows the word (like &):
function removeWord(url, text) {
const re = new RegExp(`,${text}(&|,|$)|(=)${text},`, 'g');
return url.replace(re, '$1$2');
}
const url = "http://localhost.com/?color=Red,Blue,Green&size=X,L,M,S"
console.log(removeWord(url, "Green"));
I'm doing a tracking application for my company and I really need your help
I've got some strings that display it wrong
I'll get the postcode/zipcode and the city name and the "function" (for example distrubition basis)
The string I get is something like that (it's swiss and the format is postcode cityname function)
place = "5506 MägenwilDistributionsbasis";
now postcode is "5506"
cityname is "Mägenwil"
function is "Distributionsbasis"
my question is how can I split the cityname and function (for this example now)?
is it possible to do it with regex or an if statement?
You can split the string using the following regexp:
var myString = "5506 MägenwilDistributionsbasis";
var units = /(\d+ )([A-Z][^A-Z]+)(.+)/g.exec(myString);
Check out contents of array units: there you see units[0] is the whole string, and units[1], units[2], units[3] are what you need.
Note According to comments I must say, it's just a draft for possible solution to let you understand how to start working on the problem in JS. So when you will test your application with more complicated city names and function names in the "magic string", try to figure out what regexp fits your purposes perfectly, because ([A-Z][^A-Z]+) definitly will not match all the known city names.
You could implement that in the most primitive way. Something like this:
place = "5506 MägenwilDistributionsbasis";
var codeAndNameAndFunction = place.split(" ");
var code = codeAndNameAndFunction[0];
var nameAndFunction = codeAndNameAndFunction[1];
var startOfTheFunction;
for (var i = 1, len = nameAndFunction.length; i < len; i++) {
myCharacter = nameAndFunction.charCodeAt(i);
if (myCharacter >= 65 && myCharacter <= 90) {
startOfTheFunction = i;
break;
}
}
var name = nameAndFunction.slice(0, startOfTheFunction);
var functionName = nameAndFunction.slice(startOfTheFunction,nameAndFunction.length);
This is a slight modification of Florian Peschka's answer:
You can split the string using the following regexp:
var myString = "5506 Yverdon-les-BainsDistributionsbasis";
var units = /(\d+ )(.+)([A-Z][^A-Z]+)/g.exec(myString);
Check out contents of array units: there you see units[0] is the whole string, and units[1], units[2], units[3] are what you need.
Note that this will only work if the "function" name is always in the form of Capital Letter followed by Non-capital letters.
I am trying to find matching patterns for the string that a user enters in to textbox, i was successful with the code in most cases with my code, bt ive found in some cases, it doesnt return all the needed results. I am attaching a jsfiddle link to show its wrking, I will also paste the code for future references
http://jsfiddle.net/faphf/2/
$("#facetSearchBox").live("keyup",
function() {
$("#test").empty();
facetSearch();
});
function facetSearch(){
var facetSearchTerm = $("#facetSearchBox").val();
facetSearchTerm = facetSearchTerm.toLowerCase();
var inputArray=["mark zuckerberg","ben s bernanke","ben bernanke","sven grundberg", "michael bloomberg","robert powell","kenneth lieberthal","frank boulben"];
var re = new RegExp(facetSearchTerm, "ig");
var outputArray = inputArray.filter(function(item) {
return re.test(item);
});
for(var k=0; k<outputArray.length;k++){
$("#test").append(outputArray[k] + "<br>" );
}
}
Try searching ben, it will not return all the desired results... it would be helpful if you could help me tell what is wrong with the code?
Remove the global modifier g from your Regular expression. It should work fine after that.
var re = new RegExp(facetSearchTerm, "i");
Test Link: http://jsfiddle.net/faphf/5/
EDIT:
Why RegExp with global flag in Javascript give wrong results?
Use:
var re = new RegExp( facetSearchTerm, "i");
See:fiddle
For word boundary matching:
var re = new RegExp("\\b" + facetSearchTerm, "i");
See:fiddle