javascript regex for ip address with asterisk masking - javascript

I would like to make a regular expression for an IP address with asterisk(*)
which matches these below:
The digit 127.0 could be any number between 0 to 255.
**[TRUE]**
127.*.*.*
127.0.*.*
127.0.0.*
**[FALSE]**
127.*.*.1
127.*.0.1
127.0.*.1
What I have made until now is...and of course, failed to make it out.
I totally got lost..
_regex = function(value) {
var _match = /^(?:(\d|1\d\d|2[0-4]\d|25[0-5]))\.(?:(\*|\d|1\d\d|2[0-4]\d|25[0-5]))\.(\*|(?:\d{1,2}(?:.\d{1,3}?)))\.(\*|(?:\d{1,3}(?:\*?)))$
if(_match.test(value)){
//do something;
}
}
If you give me any chance to learn this, would be highly appreciated.
Thanks.

I think what you are looking for is a negative look ahead to make sure no number follows an asterisk.
Like so: (\*(?!.*\d))
working example:
var ips = [
'127.*.*.*',
'127.0.*.*',
'127.0.0.*',
'127.*.*.1',
'127.*.0.1',
'127.0.*.1'
];
var regex = /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|(\*(?!.*\d)))(\.|$)){4}$/;
for(var i = 0; i < ips.length; i++){
console.log(ips[i] + ': ' + regex.test(ips[i]));
}

Related

How to remove a pattern in JS Regex?

The following code hides all webpages of a certain website and mocks the website.
let sites = ['mako.co.il', 'walla.co.il'];
for (let i = 0; i < sites.length; i++) {
if (window.location.href.indexOf(sites[i]) != -1 ) {
alert(` Enough with this ${sites[i]} garbage! `);
}
}
It displays domain.tld this way:
"Enough with this domain.tld garbage!".
How could I strip away the .tld, so the final outcome would be:
"Enough with this domain garbage!".
A /[domain]#.2,/ regex might unmatch tld's like .com or co.uk and only "domain" will appear on the alert, but I don't know how to implement such regex to the sites[i] in the confirm.
Do you know?
It depends how complex your strings can get, but a simple match for domains could be something as follows:
str.replace(/(\.[a-zA-Z]{1,3}){1,2}/, '')
This will work for most examples of "domain.com", "domain.co.uk", "domain.es". You might be able to find a better regex, but the idea would be the same.
Need to say, that it's a long and ugly way, but I want to show you, that it's possible without regex:
function splitDomain(str) {
var beforeDomain = str.split(" domain");
var afterDomain = beforeDomain[1].split(" ").splice(1, 1);
beforeDomain.splice(1, 1);
beforeDomain.push("domain")
afterDomain.forEach(function(item) {
beforeDomain.push(item);
})
var final = beforeDomain.join(" ")
console.log(final);
}
splitDomain("Enough with this domain.tld shit!");
splitDomain("Enough with this domain.co.uk shit!");
splitDomain("Enough with this domain.com shit!");

Making secret language useing charAt

I need to make a textbox with in there a word when i click on a button that word needs to convert into numbers useing charAt and that number needs to get +2 and than converted back into words and that word needs to get alerted i dont know what to do i find this really hard i made a function that is useless but i just want to show you what i did please help :)
function codeer(){
var woord2 = document.getElementById("woord")
var woordterug = woord2.charAt(0)
var woord234 = document.getElementById("woord");
var woord23 = woord234.charAt(str.length+2);
}
You could get the char code with String#charCodeAt from the character add two and build a new string with String.fromCharCode.
function codeer() {
var woord = document.getElementById("woord").value,
coded = '',
i;
for (i = 0; i < woord.length; i++) {
coded += String.fromCharCode(woord.charCodeAt(i) + 2);
}
console.log(coded);
}
<input id="woord" /> <button onclick="codeer()">cooder</button>
You should search the internet for a JavaScript rot13 example. In that code, you just need to replace the 13 with a 2, and it should work.

.replace method in JavaScript and duplicated characters

I'm trying to use JavaScript to insert HTML ruby characters on my text. The idea is to find the kanji and replace it with the ruby character that is stored on the fgana array. My code goes like this:
for (var i = 0; i < kanji.length; i++) {
phrase = phrase.replace(kanji[i],"<ruby><rb>" + kanji[i] + "</rb><rt>" + fgana[i] + "</rt></ruby>");
}
It does that just fine when there aren't duplicated characters to be replaced, but when there are the result is different from what I except. For example, if the arrays are like this:
kanji = ["毎朝","時","時"]
fgana = ["まいあさ"、"とき"、"じ"]
And the phrase is あの時毎朝6時におきていた the result becomes:
あの<ruby><rb><ruby><rb>時</rb><rt>じ</rt></ruby></rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 時 におきていた。
Instead of the desired:
あの<ruby><rb>時</rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 <ruby><rb>時</rb></ruby></rb><rt>じ</rt> におきていた。
To illustrate it better, look at the rendered example:
Look at how the first 時 receives both values とき and じ while the second receives nothing. The idea is to the first be とき and the second じ (as Japanese has different readings for the same character depending on some factors).
Whats might be the failure on my code?
Thanks in advance
It fails because the char you are looking for still exists in the replaced version:
...replace(kanji[i],"<ruby><rb>" + kanji[i]...
And this one should work:
var kanji = ["毎朝", "時", "時"],
fgana = ["まいあさ", "とき", "じ"],
phrase = "あの時毎朝 6 時におきていた",
rx = new RegExp("(" + kanji.join("|") + ")", "g");
console.log(phrase.replace(rx, function (m) {
var pos = kanji.indexOf(m),
k = kanji[pos],
f = fgana[pos];
delete kanji[pos];
delete fgana[pos];
return "<ruby><rb>" + k + "</rb><rt>" + f + "</rt></ruby>"
}));
Just copy and paste into console and you get:
あの<ruby><rb>時</rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 <ruby><rb>時</rb><rt>じ</rt></ruby>におきていた
Above line is a bit different from your desired result thou, just not sure if you indeed want this:
...6 <ruby><rb>時</rb></ruby></rb><rt>じ</rt>...
^^^^^ here ^ not here?

Regex for a word that repeats only the chars i provide?

Ok so what im trying to do is match words like "lol" and "lollll" and "llllol" and "llllooooollll" and "loool" but not "pfftlol" or "lolpfft" etc.
my current code is
_.each(req.room._settings.automod.cussing.words, function(word)
{
if(req.message.text.match(new RegExp('\\b'+word.split('').join('+?')+'\\b', 'gi')))
{
if(req.user && req.user.cache.automod.cussing === 0)
{
req.user.cache.automod.cussing = 1;
req.write(req.user.name+", Please refrain from cussing in your messages this is your first and only warning next time you will be deleted.");
req.room.delLastUser(req.user.name, 1);
}
else
{
req.room.delLastUser(req.user.name, 1);
}
}
});
and out of it
req.message.text.match(new RegExp('\\b'+word.split('').join('+?')+'\\b', 'gi'))
also lets say that req.room._settings.automod.cussing.words is ['lol','what'] since i dont want to list actual cuss words
and req.message.text is 'hah lollll hey'
also this is going through an _.each statement or foreach
I'm using NodeJS
right now it returns the word as long as it partially matches
anyone know what I'm doing wrong?
The answer from Ismael Miguel is correct
/\b(l)+(o)+(l)+\b/
which looks like this in my code
var reg = '\\b('+cuss.split('').join(')+(')+')+\\b';
req.message.text.match(new RegExp(reg, 'gi'));
Try this regex:
/.*\b(l+o+l+)\b.*/
var strings = ["who is lol", "looolll am i", "rofl llllooll", "pfftlol", "lolwho", "anotherlol", "lllllol hehe"];
for(var i = 0; i < strings.length; ++i){
var match = strings[i].match(/.*\b(l+o+l+)\b.*/);
if (match)
document.write( match[0] + "<br>") ;
}

regex for money values in JavaScript

Been out of the regex game for a while. Trying to come up with something that will allow the user to enter a money value either with/without dollar sign or with/without commas. For example, all the of the following values should be valid:
5
5.1
5.10
$5
500,000
500,000.1
500,000.10
$100,000,000.50
etc....
Could someone please help me out?
This should work:
isValid = str.search(/^\$?[\d,]+(\.\d*)?$/) >= 0;
A little more strict with comma placement (would reject 3,2.10, for example):
isValid = str.search(/^\$?\d+(,\d{3})*(\.\d*)?$/) >= 0;
To get a number out of it:
if(isValid) {
var num = Number(str.replace(/[\$,]/g, ''));
...
}
I didn't Test Driven Developement, TDD, for this one using the Qunit framework.
TDD overview http://net.tutsplus.com/tutorials/javascript-ajax/test-driven-javascript-development-in-practice/
1st: Write tests.
2nd: Watch tests fail.
3rd: Make test pass.
4th: Refactor.
var moneyTest_RE = /^\$?\d+((,\d{3})+)?(\.\d+)?$/;
test("test money format for valid values", function () {
var moneyArr = ["5","5.1","5.10","$5","500,000","500,000.1","500,000.10","$100,000,000.50", "500,000,100" ];
var i = moneyArr.length;
while( i-- ){
equal( moneyTest_RE.test( moneyArr[ i ] ), true, moneyArr[ i ] + " didn't match completely." );
}
});
test("test money format for invalid values", function () {
var moneyArr = ["5..","$$5.1",".5.10","$5.2.","50,0,000",",500,000.1","500,000,10,","$1,00,000,000.50", "500,000,10"];
var i = moneyArr.length;
while( i-- ){
equal( moneyTest_RE.test( moneyArr[ i ] ), false, moneyArr[ i ] + " didn't match completely." );
}
});
Here's one possible solution to your problem.
var moneyTest_RE = /^\$?\d+((,\d{3})+)?(\.\d+)?$/;
Demo here: http://jsfiddle.net/vpyV6/
I forgot to refactor though.
^(\$?\d{1,3}(?:,?\d{3})*(?:\.\d{2})?|\.\d{2})?$
This one took a while, but I finally got something fully functional. It allows for cases such as 100.00, .35, $1.35, etc. While excluding entries with misplaced commas, too many numbers in between or before commas, or too many numbers after the decimal point.
You can play around with it here
var currencyRegex = /^[$£€]\d+(?:\.\d\d)*$/g;
Example: $10 or £10 0r €10 but if you use simple 10 this will be wrong
Perhaps this?
http://refiddle.com/2tg
(\$?(:?\d+,?.?)+)
Also, http://refiddle.com/2ti ; a longer version that doesn't match numbers like 123,45.4.3
^(\$?(:?\d+,?)+(?:.?\d+)?)$

Categories

Resources