Test if all given char's are in string - Javascript - javascript

I'm looking for smart, fast and simple way to check if the string contains all of the predefined char's.
For example:
var required = 'cfov'; //These are the char's to test for.
var obj = {valid: 'vvcdfghoco'}; //Valid prop can contains any string.
//what I have so far::
var valid = obj.valid, i = 0;
for(; i < 4; i++) {
if(valid.indexOf(required.chatAt(i)) === -1) {
break;
}
}
if(i !== 3) {
alert('Invalid');
}
Can we do it in RegExp? if yes, any help plz!
Thanks in Advance.

You can build a lookahead regex for your search string:
var re = new RegExp(required.split('').map(function(a) {
return "(?=.*" + a + ")"; }).join(''));
//=> /(?=.*c)(?=.*f)(?=.*o)(?=.*v)/
As you note that this regex is adding a lookahead for each character in search string to make sure that all the individual chars are present in the subject.
Now test it:
re.test('vvcdfghoco')
true
re.test('vvcdghoco')
false
re.test('cdfghoco')
false
re.test('cdfghovco')
true

You can do this way:
var required = 'cfov'; //These are the char's to test for.
var valid = 'vvcdfghoco'; //Valid prop can contains any string.
var regex = new RegExp("^[" + valid + "]*$");
/* this line means:
from start ^ till * the end $ only the valid characters present in the class [] */
if (required.match(regex)) {
document.write('Valid');
}
else {
document.write('Invalid');
}
Hope it helps.

Related

How can I create a pallindrome code in JavaScript?

So I am trying to create a code for palindrome this is how I tried. Is there another or better way of doing it?
But now it only shows that if the first value is equal or not and shows true or false?
var inpo= prompt("Please enter to check if palindrome")
var inp = parseFloat(inpo)
var a = inpo.split('')
var inpo2 = a.reverse()
var len= inpo.length
for (var i =0;i< len ;i++) {
if (inpo[i] == inpo2[i] )
alert("True")
else
alert("False")
}
A way to check if a word or an entire phrase is a palindrome or not:
function isPalindrome(str) {
// Escape the string: Eliminate punctuation and spaces, enforce lower case
let escaped = str.replace(/[^A-Za-z0-9_]/g,"").toLowerCase();
// Reverse the escaped string
let reversed = escaped.split('').reverse().join('');
//compare
return escaped == reversed;
}
console.log(isPalindrome('Level'));
console.log(isPalindrome('Red rum, sir, is murder'));
I hope the comments serve well as an explanation.
Also, you have a prompt example in THIS jsfiddle.
If you are creating a palindrome checker code, here is a simple way to do it. Split, reverse then join.
str1 = "xxaa";
str2 = str1.split('').reverse().join("");
if (str1 == str2) {
alert("good");
} else {
alert("not");
}
You can check the single character from the string consuming 1 character from right and another from left until you will find either the string is finished or there are 2 inequal character. I implemented with a classical for loop.
Note that bracket notation for strings [] is only recently supported, you can use charAt if memory serves me right
let inp = "otdto";
console.log(isPalindrome(inp));
function isPalindrome(inp) {
const len = inp.length;
for (let i = 0; i < Math.floor(len / 2); i++)
if (inp[i] != inp[len - i - 1])
return false;
return true;
}

Multiple ip addresses in single string

I have that kind of datas :
172.12.1.3;185.16.6.13;...
And sometimes the submask so it could be :
172.12.1.3;185.16.6.13/32;172.12.1.4;...
So I wanted to use regex (in js) to be sure each ip address is correct using ";" as separator.
It should not be too difficult, but even with a few research i've just manage to do something like this :
/^(((^|\.?)(1[0-9]{2}|[1-9][0-9]|[0-9]|2[0-4][0-9]|25[0-5])){4}(\;|$))*$/
Btw I know that I should, but I'm not really into regex...
Can someone give me a hand please ?
edit :
So i've tried something like this :
var poolIp = v.split(";");
var ipAddress = /^(((^|\.?)(1[0-9]{2}|[1-9][0-9]|[0-9]|2[0-4][0-9]|25[0-5])){4}(\;|$))*$/;
var ret = true;
for (var i = 0; i < poolIp.length; i++) {
var matches = ipAddress.exec(poolIp[i]);
if (!matches) {
ret = false;
}
}
return ret;
And it's way better, but ip address with submask is not valid and ip with 3 digits are valid.
You may use the following function to validate such strings of IP addresses. Note that the port number validation can be enhanced, I just check if the value is numeric.
function checkIsIPV4s(entry) {
var ips = entry.split(';'); // Split into separate IPs
for (var ip of ips) {
var blocks = ip.split(/[.\/]/); // Split with dot and slash
if(blocks.length === 5) { // If there are 5 blocks,
var last = blocks.pop(); // remove the last one
if (!/^\d+$/.test(last)) { // and check if it is numeric
return false; // if not - FALSE
}
}
if(blocks.length === 4) { // If block number is 4
var res = blocks.every(function(block) { // check each part
return parseInt(block,10) >=0 && parseInt(block,10) <= 255;
});
if (!res) {return false; } // If any part is not in 0..255 - FALSE
} else {
return false; // If block number is not 4 - FALSE
}
}
return true;
}
var str = "172.12.1.3;185.16.6.13/32;172.12.1.4;255.255.255.255";
console.log(checkIsIPV4s(str));
str2 = "172.12.1.34444;185.16.6.13/32";
console.log(checkIsIPV4s(str2));
However, there is a way to use a huge and unreadable regex, too. Adding this just to show that it is possible to do it with a regex:
/^(?:(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))\.){3}(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))(?:\/\d+)?(?:;(?:(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))\.){3}(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))(?:\/\d+)?)*$/
See the regex demo
The pattern matches:
^ - start of string
(?:(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))\.){3}(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))(?:\/\d+)? - a single IP pattern (all up to (?:\/\d+)?) with an optional port number ((?:\/\d+)?)
(?: - the non-capturing group start
; - the separator
(?:(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))\.){3}(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))(?:\/\d+)? - the single IP pattern, same as above
)* - 0 or more occurrences of the non-capturing group sequences
$ - end of string.
This should do it:
var re = /^(;?[1-9][\d]{1,2}(\.[\d]{1,3}){3}(\/[\d]{1,3})?)+$/
re.test('172.12.1.3;185.16.6.13/32;172.12.1.4') // true
re.test('172.12.1.3;185.16.6.13/32;172.12.1') // false
re.test('072.12.1.3;185.16.6.13/32;172.12.1.4') // false
Or splitting them up:
var re = /^[1-9][\d]{1,2}(\.[\d]{1,3}){3}(\/[\d]{1,3})?$/
var ip1 = '172.12.1.3;185.16.6.13/32;172.12.1.4'.split(';');
var ip2 = '172.12.1.3;185.16.6.13/32;172.12.1'.split(';');
var ip3 = '072.12.1.3;185.16.6.13/32;172.12.1.4'.split(';');
ip1.every((ip) => re.test(ip));
ip2.every((ip) => re.test(ip));
ip3.every((ip) => re.test(ip));
You can use http://regexr.com/ to test your regexp, and read about Array.every here.

how to check if a string matches a pattern with asterisk

I have a list of files:
var files = [
"user_parse_info",
"user_parse_age",
"site_render_info",
"site_parse_name"
]
Now I have string a pattern:
var pattern = "site_*_name";
This should match only the last file.
How can I check this? Maybe an RegExp?
Yes, regular expression would be a better choice for this.
var _ = require('nimble');
var files = [
"user_parse_info",
"user_parse_age",
"site_render_info",
"site_parse_name"
];
var re = /^site_.*_name$/;
var result = _.filter(files, function (val) {
return re.test(val);
});
Using a regular expression means that you would need to escape some characters like . and $, otherwise they can give false positives or keep the pattern from matching anything.
You can just split the string on the asterisk and check the parts against the string:
var parts = pattern.split('*');
if (
str.length >= parts[0].length + parts[1].length &&
str.substr(0, parts[0].length) == parts[0] &&
str.substr(str.length - parts[1].length) == parts[1])
{
// matches
}
Demo: http://jsfiddle.net/Guffa/u8XEE/

Determining whether values can potentially match a regular expression, given more input

I am currently writing an application in JavaScript where I'm matching input to regular expressions, but I also need to find a way how to match strings to parts of the regular expressions.
For example:
var invalid = "x",
potentially = "g",
valid = "ggg",
gReg = /^ggg$/;
gReg.test(invalid); //returns false (correct)
gReg.test(valid); //returns true (correct)
Now I need to find a way to somehow determine that the value of the potentially variable doesn't exactly match the /^ggg$/ expression, BUT with more input, it potentially can!
So for example in this case, the potentially variable is g, but if two more g's are appended to it, it will match the regular expression /^ggg$/
But in the case of invalid, it can never match the /^ggg$/ expression, no matter how many characters you append to it.
So how can I determine if a string has or doesn't have potential to match a particular regular expression?
Try this:
var str = "abcdefgh";
var len = str.length;
var reg = "";
for(var i = str.length - 1; i > 0; i--)
{
//replace '(' with '(?:' to make it non capturing.
reg = '(' + str[i] + reg + ')?';
}
reg = "^" + str[0] + reg + "$";
var regex = new RegExp(reg);
How about you simply "reverse" your thinking on this, and turn the "potential" into a regex, testing in the other direction, eg
var invalid = "x",
potentially = "g",
valid = "ggg",
validReg = new RegExp("^"+valid+"$"),
invalidReg = new RegExp(invalid),
potentialReg = new RegExp(potentially);
//test actual matches
validReg.test(invalid); //returns false (correct)
validReg.test(valid); //returns true (correct)
//test potential matches
potentialReg.test(valid); //returns true
invalidReg.test(valid); //returns false
Obviously the test function below isn't going to be exactly what you want ... hopefully it will give you an idea as to how to tackle the problem.
function test(reg,string){
var r = reg.exec(string);
if(r){
if(r.pop()){
return true;
}
return "potentially";
}
return false;
}
var invalid = "x",
potentially = "a",
potentially2 = "ab",
valid = "abc",
gReg = /^a(b(c)?)?$/;
alert(test(gReg,invalid)); //returns false (correct)
alert(test(gReg,potentially)); //returns "potentially" (correct)
alert(test(gReg,potentially2)); //returns "potentially" (correct)
alert(test(gReg,valid)); //returns true (correct)
There is no general solution. If the regexp is a simple string, like the one in the example (in which case there is no point in using a regexp at all), you can use simple string comparision:
var invalid = "x",
potentially = "g",
valid = "ggg";
var gReg = "ggg";
function test(t, s) {
if (t === s) return true;
if (t.indexOf(s) === 0) return "potentially";
return false;
}
test(gReg, invalid); // false
test(gReg, potentially); // "potentially"
test(gReg, valid); // true
Otherwise you can manually construct another regexp which accepts every prefix of every string gReg accepts. You will have to use ()? a lot.
function have_potential(input, valid) {
if ( (new RegExp('^' + valid + '$')).test(input) ) return false;
if ( (new RegExp(input)).test( valid ) ) return true;
return false;
}
var valid = 'aaa|bbb';
console.log( have_potential('a',valid) )
// true
console.log( have_potential('c',valid) )
// false
console.log( have_potential('aaa',valid) )
// false
Edit:
shorten version
function have_potential(input, valid) {
return ( (new RegExp(input)).test( valid ) && !(new RegExp('^' + valid + '$')).test(input) );
}
Edit2:
indexOf would be better in first place. function requires flat string inputs and "valid" may contain a list separated by "|"
function have_potential(input, valid) {
return ( valid.indexOf(input) !== -1 && !(new RegExp('^' + valid + '$')).test(input) );
}

Get everything after the dash in a string in JavaScript

What would be the cleanest way of doing this that would work in both IE and Firefox?
My string looks like this sometext-20202
Now the sometext and the integer after the dash can be of varying length.
Should I just use substring and index of or are there other ways?
How I would do this:
// function you can use:
function getSecondPart(str) {
return str.split('-')[1];
}
// use the function:
alert(getSecondPart("sometext-20202"));
A solution I prefer would be:
const str = 'sometext-20202';
const slug = str.split('-').pop();
Where slug would be your result
var testStr = "sometext-20202"
var splitStr = testStr.substring(testStr.indexOf('-') + 1);
var the_string = "sometext-20202";
var parts = the_string.split('-', 2);
// After calling split(), 'parts' is an array with two elements:
// parts[0] is 'sometext'
// parts[1] is '20202'
var the_text = parts[0];
var the_num = parts[1];
With built-in javascript replace() function and using of regex (/(.*)-/), you can replace the substring before the dash character with empty string (""):
"sometext-20202".replace(/(.*)-/,""); // result --> "20202"
AFAIK, both substring() and indexOf() are supported by both Mozilla and IE. However, note that substr() might not be supported on earlier versions of some browsers (esp. Netscape/Opera).
Your post indicates that you already know how to do it using substring() and indexOf(), so I'm not posting a code sample.
myString.split('-').splice(1).join('-')
I came to this question because I needed what OP was asking but more than what other answers offered (they're technically correct, but too minimal for my purposes). I've made my own solution; maybe it'll help someone else.
Let's say your string is 'Version 12.34.56'. If you use '.' to split, the other answers will tend to give you '56', when maybe what you actually want is '.34.56' (i.e. everything from the first occurrence instead of the last, but OP's specific case just so happened to only have one occurrence). Perhaps you might even want 'Version 12'.
I've also written this to handle certain failures (like if null gets passed or an empty string, etc.). In those cases, the following function will return false.
Use
splitAtSearch('Version 12.34.56', '.') // Returns ['Version 12', '.34.56']
Function
/**
* Splits string based on first result in search
* #param {string} string - String to split
* #param {string} search - Characters to split at
* #return {array|false} - Strings, split at search
* False on blank string or invalid type
*/
function splitAtSearch( string, search ) {
let isValid = string !== '' // Disallow Empty
&& typeof string === 'string' // Allow strings
|| typeof string === 'number' // Allow numbers
if (!isValid) { return false } // Failed
else { string += '' } // Ensure string type
// Search
let searchIndex = string.indexOf(search)
let isBlank = (''+search) === ''
let isFound = searchIndex !== -1
let noSplit = searchIndex === 0
let parts = []
// Remains whole
if (!isFound || noSplit || isBlank) {
parts[0] = string
}
// Requires splitting
else {
parts[0] = string.substring(0, searchIndex)
parts[1] = string.substring(searchIndex)
}
return parts
}
Examples
splitAtSearch('') // false
splitAtSearch(true) // false
splitAtSearch(false) // false
splitAtSearch(null) // false
splitAtSearch(undefined) // false
splitAtSearch(NaN) // ['NaN']
splitAtSearch('foobar', 'ba') // ['foo', 'bar']
splitAtSearch('foobar', '') // ['foobar']
splitAtSearch('foobar', 'z') // ['foobar']
splitAtSearch('foobar', 'foo') // ['foobar'] not ['', 'foobar']
splitAtSearch('blah bleh bluh', 'bl') // ['blah bleh bluh']
splitAtSearch('blah bleh bluh', 'ble') // ['blah ', 'bleh bluh']
splitAtSearch('$10.99', '.') // ['$10', '.99']
splitAtSearch(3.14159, '.') // ['3', '.14159']
For those trying to get everything after the first occurrence:
Something like "Nic K Cage" to "K Cage".
You can use slice to get everything from a certain character. In this case from the first space:
const delim = " "
const name = "Nic K Cage"
const result = name.split(delim).slice(1).join(delim) // prints: "K Cage"
Or if OP's string had two hyphens:
const text = "sometext-20202-03"
// Option 1
const opt1 = text.slice(text.indexOf('-')).slice(1) // prints: 20202-03
// Option 2
const opt2 = text.split('-').slice(1).join("-") // prints: 20202-03
Efficient, compact and works in the general case:
s='sometext-20202'
s.slice(s.lastIndexOf('-')+1)
Use a regular expression of the form: \w-\d+ where a \w represents a word and \d represents a digit. They won't work out of the box, so play around. Try this.
You can use split method for it. And if you should take string from specific pattern you can use split with req. exp.:
var string = "sometext-20202";
console.log(string.split(/-(.*)/)[1])
Everyone else has posted some perfectly reasonable answers. I took a different direction. Without using split, substring, or indexOf. Works great on i.e. and firefox. Probably works on Netscape too.
Just a loop and two ifs.
function getAfterDash(str) {
var dashed = false;
var result = "";
for (var i = 0, len = str.length; i < len; i++) {
if (dashed) {
result = result + str[i];
}
if (str[i] === '-') {
dashed = true;
}
}
return result;
};
console.log(getAfterDash("adfjkl-o812347"));
My solution is performant and handles edge cases.
The point of the above code was to procrastinate work, please don't actually use it.
To use any delimiter and get first or second part
//To divide string using deimeter - here #
//str: full string that is to be splitted
//delimeter: like '-'
//part number: 0 - for string befor delimiter , 1 - string after delimiter
getPartString(str, delimter, partNumber) {
return str.split(delimter)[partNumber];
}

Categories

Resources