I am currently trying to figure out how to solve the above named problem.
Specifically I want to check if the string does not contain the word "stream" both in capital and lowercase letters.
Here's my code so far:
if (((gewaesser_name1.includes("Stream") == "false") ||
(gewaesser_name1.includes("stream") == "false")) &&
((gewaesser_name2.includes("Stream") == "false") ||
(gewaesser_name2.includes("stream") == "false")))
{var a= "..."}
The code does obviously not work as the results are not what I expect them to be.
I also tried to use the indexOf method before using the following syntax variations:
gewaesser_name2.indexOf("stream") == -1
gewaesser_name2.indexOf("stream") < 0
None of these variations seem to work for me. Could anyone please give me a hint what's the problem here? I used the indexOf method before many times but always when I wanted to check if a string did contain a specific word, not the other way round.
I suggest to use String+toLowerCase and check with String#indexOf, because it works in every browser.
if (gewaesser_name1.toLowerCase().indexOf("stream") === -1 && gewaesser_name2.toLowerCase().indexOf("stream") === -1) {
var a = "..."
}
indexOf() is the correct approach and the case issue can be easily resolved by forcing the test string to lower or upper case before the test using .toLowerCase() or .toUpperCase():
const lookupValue = "stream";
const testString1 = "I might contain the word StReAm and it might be capitalized any way.";
const testString2 = "I might contain the word steam and it might be capitalized any way.";
function testString(testData, lookup){
return testData.toLowerCase().indexOf(lookup) === -1;
}
function prettyPrint(yesNo){
return "The string does" + (yesNo ? " NOT" : "") + " contain \"stream\" in some form."
}
console.log(prettyPrint(testString(testString1, lookupValue)));
console.log(prettyPrint(testString(testString2, lookupValue)));
You may want to compare the returned results of your include() with strictly equal operands, === false or === true, it's much better practice however not really needed for this, just looks like you might benefit from knowing the different as comparing boolean to a string is an odd thing to do. I'd also not be checking "Stream" and "stream" try using toLowerCase() instead like so, var str1_check = gewaesser_name1.toLowerCase();
I'd check for stream using the lowercase "stream" as your new strings will all be in lower case, as well you want them to be separate from your initial variables as you may not want those names forced to lowercase. I'd use str1_check.includes("stream") to check if this string has the string "stream" in it, because this result is truthy or falsey you can perform your check like so.
if(str1_check.includes("stream")) {
//this string contained stream
}
I looks like your if logic here was if the first name doesn't contain "stream" or name 1 and 2 do not contain stream but your checking name 1 with lowercase "stream" and name 2 with uppercase "stream". it looks like you just want both names not to contain stream, this can be much more easily performed like this.
var str1_check = gewaesser_name1.toLowerCase(),
str2_check = gewaesser_name2.toLowrCase();//this way you're not making multiple toLowerCase calls in your conditional and maintain the state of your two names.
if(!str1_check.includes("stream") && !str2_check.includes("stream")){
//your code on truthey statement
}
Thanks for the fast feedback guys, the code is now running perfectly fine!
I am using the following code:
`if (gewaesser_name1.toLowerCase().indexOf("stream") === -1 && gewaesser_name2.toLowerCase().indexOf("stream") === -1)
{var a = "does NOT contain stream"}
else {var a= "does contain stream"}
`
this is a operation you can do in regex:
const testString1 = "I might contain the word StReAm and it might be capitalized any way.";
const testString2 = "I might contain the word steam and it might be capitalized any way.";
const re = /stream/i
console.log( !!(testString1.match(re) ));
console.log( !!(testString2.match(re) ))
I would prefer to use javascript RegExp like this:
function includesMatch(lookupValue, testString){
var re = new RegExp(lookupValue, 'i'); //Here the 'i' means that we are doing a case insensitive match
return testString.match(re) !== null
}
var lookup = "stream";
var test1 = "do I have a StrEAm in me?";
var test2 = "well at least I don't";
console.log(includesMatch(lookup, test1));
console.log(includesMatch(lookup, test2));
Related
So I've got a proof-of-concept conjugation practice application I'm building, with Vue.js. One of the key elements is that when you type in an answer to a conjugation, it compares the input text with String.startswith(). This is great until the string has unicode characters. It seems that almost always the unicode characters that you input are different than the ones in the database. You can actually visually see in this node CLI example that the version I type in the "ț" character is literally a different character than the one in the database "ţ".
Here is an output of the typed input, it's value and unicode value vs. the comparison:
input: anunț // anun\u21B
comparison: anunţ // anun\u163
I've tried things like .normalize() but it doesn't seem to affect either the inputted string, or the comparison string.
> var input = 'anunț'
> var comparison = 'anunţ'
> input === comparison
false
> input.normalize() === comparison
false
> input.normalize() === comparison.normalize()
false
> input === comparison.normalize()
false
/// etc etc with NFC, NFD, NFKC, NFKD forms
> input.normalize()
'anunț'
> comparison.normalize()
'anunţ'
// i've also tried .normalize() with the string decoded into unicode
I've tried converting to unicode and manually replacing one set of strings, but it only goes so far--- and brings up it's own bunch of issues --- including that sometimes when you type in the answer it will start to have issues doing a positive comparison until the entire string is entered.
Finally I've started to try regex comparisons, but I think this may also be another rabbit hole distraction.
Stripped down to it's most basic logic without any of the above attempts, this is the crux of what I am trying to do, for context:
if (this.conjugation.startsWith(this.input)) {
this.status = "correct";
} else {
this.status = "incorrect";
}
if (conjugation === val) {
// okay, we are done
}
Any thoughts of how I can get around this? I am currently testing this with Romanian verbs, so the characters appear to be in the following unicode ranges:
\u0000-\u007F, \u0180-\u024F, \u0100-\u017F
You can use Intl.Collator to construct a collator that only cares about some differences:
var word1 = "anunț"; // anun\u21B
var word2 = "anunţ"; // anun\u163
var collator = new Intl.Collator("ro", { sensitivity: "base" });
console.log(word1 === word2); // the words are not equal
console.log(collator.compare(word1, word2) == 0); // ... but they are "equal enough"
These two characters are very similar, but they are distinct. One has space between the t and the lower comma mark like part of the symbol.
I'm studying regular expressions in Javascript
I've seen many ways to do exclusive matching through the OR operator with [] and | within groups ().
I can't understand how to achieve the AND behavior with regular expressions. I've done some research but I didn't find what I need.
Here an example. I have the following string: kata. I want to compare it with another string: steak. The goal is to return true if all the letters in steak is contained in kata. If I use this regular expression [steak] it returns true but actually it should return false because in kata there is no "s".
Example 2. String1 = scriptsjava, string2 = javascript, result = true (because string2 is contained in string1)
Example 3. String1 = jscripts, string2 = javascript, result = false (because string2 is not fully contained in string1)
Example 4. String1 = rkqodlw, string2 = world, result = true (because the string world is in the first string)
I thought that using regular expressions is the best way and I considered string2 as a pattern. My solution to this problem is the following
var validate=true;
var counter = 0;
str2.split("").map(val => {
counter++;
var char = new RegExp(val);
if (char.test(str1) === false) { validate = false;} else
{
str1 = str1.slice(0, counter+1) + str1.slice(counter+1,str1.length);
console.log(str1);
}
});
return validate;
I think is not the most efficient though. Do you have a better solution for this?
You want a set comparison, specifically a superset check. Simple with a Set:
let s1 = 'javascript';
let s2 = 'scriptsjava';
Set.prototype.isSuperset = function(subset) {
for (var elem of subset) {
if (!this.has(elem)) {
return false;
}
}
return true;
}
console.log(new Set(s1).isSuperset(new Set(s2)));
Well this is my second answer, I might remove the previous answer later on, if I see this seems to be helpful for you.
Although there are some good answer being posted but yet as I can see that you want to have a hold on AND operation in regex, therefore you want a regexAND answer. Thus I am going to give you an answer that works according to your need. But if you want me to be frank, then I would say, for your requirement , regex operation is kind of the last option that I would want to go for.
Now comes the answer:
For each pair , say str1, and str2. You want to see if each character of str2 is present in str1.
thus you can make AND operation in the form of positive lookahead for each character for the entire string of str2 and see if all these exists in str1 or not.
each positie lookahead would look likhe this: (?=.*w)
when written one beside another like the regex mentioned bellow they work as AND.
For example:
str1="rkqodlw"
str2="world"
make a regex by str2 in the following way:
^(?=.*w)(?=.*o)(?=.*r)(?=.*l)(?=.*d).*$
and see if that matches with str1
like this way:
function compare(str1,str2)
{
var regexAnd=str2.split("").join(")(?=.*");
var regexStr="^"+"(?=.*"+regexAnd+").*$";
console.log(regexStr); // prints the entire and condition
var re = new RegExp(regexStr,"gm");
return re.test(str1);
}
console.log(compare("scriptsjava","javascript"));
console.log(compare("jscripts","javascript"));
console.log(compare("rkqodlw","world"));
I am currently trying to figure out how to solve the above named problem.
Specifically I want to check if the string does not contain the word "stream" both in capital and lowercase letters.
Here's my code so far:
if (((gewaesser_name1.includes("Stream") == "false") ||
(gewaesser_name1.includes("stream") == "false")) &&
((gewaesser_name2.includes("Stream") == "false") ||
(gewaesser_name2.includes("stream") == "false")))
{var a= "..."}
The code does obviously not work as the results are not what I expect them to be.
I also tried to use the indexOf method before using the following syntax variations:
gewaesser_name2.indexOf("stream") == -1
gewaesser_name2.indexOf("stream") < 0
None of these variations seem to work for me. Could anyone please give me a hint what's the problem here? I used the indexOf method before many times but always when I wanted to check if a string did contain a specific word, not the other way round.
I suggest to use String+toLowerCase and check with String#indexOf, because it works in every browser.
if (gewaesser_name1.toLowerCase().indexOf("stream") === -1 && gewaesser_name2.toLowerCase().indexOf("stream") === -1) {
var a = "..."
}
indexOf() is the correct approach and the case issue can be easily resolved by forcing the test string to lower or upper case before the test using .toLowerCase() or .toUpperCase():
const lookupValue = "stream";
const testString1 = "I might contain the word StReAm and it might be capitalized any way.";
const testString2 = "I might contain the word steam and it might be capitalized any way.";
function testString(testData, lookup){
return testData.toLowerCase().indexOf(lookup) === -1;
}
function prettyPrint(yesNo){
return "The string does" + (yesNo ? " NOT" : "") + " contain \"stream\" in some form."
}
console.log(prettyPrint(testString(testString1, lookupValue)));
console.log(prettyPrint(testString(testString2, lookupValue)));
You may want to compare the returned results of your include() with strictly equal operands, === false or === true, it's much better practice however not really needed for this, just looks like you might benefit from knowing the different as comparing boolean to a string is an odd thing to do. I'd also not be checking "Stream" and "stream" try using toLowerCase() instead like so, var str1_check = gewaesser_name1.toLowerCase();
I'd check for stream using the lowercase "stream" as your new strings will all be in lower case, as well you want them to be separate from your initial variables as you may not want those names forced to lowercase. I'd use str1_check.includes("stream") to check if this string has the string "stream" in it, because this result is truthy or falsey you can perform your check like so.
if(str1_check.includes("stream")) {
//this string contained stream
}
I looks like your if logic here was if the first name doesn't contain "stream" or name 1 and 2 do not contain stream but your checking name 1 with lowercase "stream" and name 2 with uppercase "stream". it looks like you just want both names not to contain stream, this can be much more easily performed like this.
var str1_check = gewaesser_name1.toLowerCase(),
str2_check = gewaesser_name2.toLowrCase();//this way you're not making multiple toLowerCase calls in your conditional and maintain the state of your two names.
if(!str1_check.includes("stream") && !str2_check.includes("stream")){
//your code on truthey statement
}
Thanks for the fast feedback guys, the code is now running perfectly fine!
I am using the following code:
`if (gewaesser_name1.toLowerCase().indexOf("stream") === -1 && gewaesser_name2.toLowerCase().indexOf("stream") === -1)
{var a = "does NOT contain stream"}
else {var a= "does contain stream"}
`
this is a operation you can do in regex:
const testString1 = "I might contain the word StReAm and it might be capitalized any way.";
const testString2 = "I might contain the word steam and it might be capitalized any way.";
const re = /stream/i
console.log( !!(testString1.match(re) ));
console.log( !!(testString2.match(re) ))
I would prefer to use javascript RegExp like this:
function includesMatch(lookupValue, testString){
var re = new RegExp(lookupValue, 'i'); //Here the 'i' means that we are doing a case insensitive match
return testString.match(re) !== null
}
var lookup = "stream";
var test1 = "do I have a StrEAm in me?";
var test2 = "well at least I don't";
console.log(includesMatch(lookup, test1));
console.log(includesMatch(lookup, test2));
I have the following String :
var resultLine= "[UT] - GSM incoming call : STEP 1 - Simulate reception from server (1)Rerun3713 msAssertion ok"
And the following code which is responsible to check of the String matched with the Regex :
var resultRE = /^([ \w-]*: )?(.+) \((\d+), (\d+), (\d+)\)Rerun/;
var resultMatch = resultLine.match(resultRE);
if (resultMatch) {
return true;
} else {
return false;
}
In this case, i have an error in my Regex because i always get "false".
Where is my mistake ?
I would recommend the following pattern based on what it appears you are looking for:
var resultRE = /^([\[ \w\]-]*: )(.+) \(([0-9, ]*)\)Rerun(.*)$/
This should force all capture groups to exist, even if they are empty, and will allow for multiple numbers before Rerun as you seem to expect.
This matches nothing in your string
([ \w-]*: )?
Since it was optional, that doesn't matter because it gets caught by the all inclusive
(.+)
If you were trying to match the [UT] part with it's separator, it would look something like this
(\[\w+\][\s\-]*)?
As noted in the comments, you only have one number in parentheses but your regex requires three sets of them, separated by commas. This will allow any number of numbers, separated by commas indefinitely (I don't know if there's a limit or not).
\((\d+,\s)*(\d+)\)
If you need something more specific, you'll have to be more specific about what template your matching, not a specific case. But the best I can figure with what you've provided is
^(\[\w\][\s\-]*)?(.+)\((\d+,\w)*(\d+)\)Rerun
var resultRE = /\((\d+)(?:, (\d+))?(?:, (\d+))?\)Rerun/;
if (resultRE.test(resultLine)) {
var num1 = RegExp.$1,
num2 = RegExp.$2,
num3 = RegExp.$3;
}
I am trying to learn JavaScript... I have function like, I take the format user id field... which is an email address and try to check if it matches below condition. However even thought I give the user name >3 and domain as gmail.com, I still get false return...Can someone please check and let me know why it is going into the if loop, do I have to trim the text or something.
Also if you can tell me how to write this effectively using jQuery that would help me learn. But if you think I am mixing two thing here... My priority is first question above.
function isValidate(eltt) {
var flag = true;
var upos = eltt.indexOf("#");
var uendpos = eltt.indexOf(".com");
var totlength = eltt.length;
var domain = eltt.slice(upos,totlength);
if ( upos < 3 | domain!="gmail.com" | uendpos=== -1) {
flag=false;
}
return flag;
}
First, the problem is that you're using | instead of ||. (The | is a bitwise or, which in this case will yield a basically random result by combining the bits of the binary representation of your conditions. Chances are, you'll never need |; so use || and forget that | even does anything by itself.)
Second, this validation would be easier with a regular expression:
if (!eltt.match(/^.{3,}#gmail\.com$/)) {
return false;
}
That is, it must start with (^) at least three characters .{3,}, followed by the literal text #gmail.com, with nothing after it ($).