Multiple OR Strings - javascript

I cannot find out how to pass multiple strings in an If statement.
Here is my Code :
var date = new Date();
if (document.getElementById("postcode-entry").value == ("G74" || "G75")) {
if (date.getHours() < 8 ) {
window.alert("Sorry we are not open at the moment, please try again later.");
} else {
window.open("http://http://stackoverflow.com");
}
} else {
window.alert("Sorry we do not Delivery to your area, please collect from store");
}
How can i do this ?

The phrase ("G74" || "G75") forces a boolean evaluation on each string, and both will return true always.
So you would need to do something like this:
var myvar = document.getElementById("postcode-entry").value;
if(myvar === "G74" || myvar === "G75")

i am not sure if you want to follow this approach but try using the following-
var strArr = [ 'G74', 'G75' ];
if( strArr.indexOf( document.getElementById("postcode-entry").value ) !== -1 ) {
// Your normal code goes here
}
Using this, you can have n number of string tested in a single statement inside if.

This should do
var post_code = document.getElementById("postcode-entry").value;
if (post_code == "G74" || post_code == "G75")

I have never seen this before. Perhaps you can use the switch statement
But in your case I would recomment the following:
var poscode = document.getElementById("postcode-entry").value
if (postcode === "G74" || postcode === "G75") ......

Related

Splitting word into syllables in javascript

My intention is to build a simple process with which I can split the word into syllables. The approach is to split the word whenever the vowel occurs. However, the trouble is when a consonant is not followed by a vowel, in such a case the split occurs at that consonant.
My test cases are as follows:
hair = ["hair"]
hairai = ["hai", "rai"]
hatred = ["hat", "red"]
In the first example hair is one syllable, as the final consonant is not followed by a vowel, similarly, in the final example, the "t" is followed by an r and so should considered along "ha" as one syllable.
In the second example, ai is considered as one vowel sound and so hai will become one syllable.
More examples include
father = ["fat", "her"]
kid = ["kid"]
lady = ["la","dy"]
Please note that, I am using simplistic examples as the ENglish language is quite complex when it comes to sound
My code is as follows
function syllabify(input) {
var arrs = [];
for (var i in input) {
var st = '';
var curr = input[i];
var nxt = input[i + 1];
if ((curr == 'a') || (curr == 'e') || (curr == 'i') || (curr == 'o') || (curr == 'u')) {
st += curr;
} else {
if ((nxt == 'a') || (nxt == 'e') || (nxt == 'i') || (nxt == 'o') || (nxt == 'u')) {
st += nxt;
} else {
arrs.push(st);
st = '';
}
}
}
console.log(arrs);
}
syllabify('hatred')
However, my code does not even return the strings. What am I doing wrong?
Problems with your current approach
There are a number of problems with your code:
First thing in the loop, you set st to an empty string. This means that you never accumulate any letters. You probably want that line above, outside the loop.
You are trying to loop over the indexes of letters by using i in input. In JavaScript, the in keyword gives you the keys of an object as strings. So you get strings, not numbers, plus the names of some methods defined on strings. Try var i = 0; i < input.length; i++ instead.
Maybe not the direct cause of the problems, but still - your code is messy. How about these?
Use clearer names. currentSyllable instead of st, syllables instead of arrs and so on.
Instead of a nested if - else, use one if - else if - else.
You repeat the same code that checks for vowels twice. Separate it into a function isVowel(letter) instead.
A new approach
Use regular expressions! Here is your definition of a syllable expressed in regex:
First, zero or more consonants: [^aeiouy]*
Then, one or more vowels: [aeiouy]+
After that, zero or one of the following:
Consonants, followed by the end of the word: [^aeiouy]*$
A consonant (if it is followed by another consonant): [^aeiouy](?=[^aeiouy])
Taken together you get this:
/[^aeiouy]*[aeiouy]+(?:[^aeiouy]*$|[^aeiouy](?=[^aeiouy]))?/gi
You can see it in action here. To run it in JavaScript, use the match function:
const syllableRegex = /[^aeiouy]*[aeiouy]+(?:[^aeiouy]*$|[^aeiouy](?=[^aeiouy]))?/gi;
function syllabify(words) {
return words.match(syllableRegex);
}
console.log(['away', 'hair', 'halter', 'hairspray', 'father', 'lady', 'kid'].map(syllabify))
Note that this does not work for words without vowels. You would either have to modify the regex to accomodate for that case, or do some other workaround.
I am weak in the ways of RegEx and while Anders example is right most of the time, I did find a few exceptions. Here is what I have found to work so far (but I am sure there are other exceptions I have not found yet). I am sure it can be RegEx'ified by masters of the art. This function returns an array of syllables.
function getSyllables(word){
var response = [];
var isSpecialCase = false;
var nums = (word.match(/[aeiou]/gi) || []).length;
//debugger;
if (isSpecialCase == false && (word.match(/[0123456789]/gi) || []).length == word.length ){
// has digits
response.push(word);
isSpecialCase = true;
}
if (isSpecialCase == false && word.length < 4){
// three letters or less
response.push(word);
isSpecialCase = true;
}
if (isSpecialCase == false && word.charAt(word.length-1) == "e"){
if (isVowel(word.charAt(word.length-2)) == false){
var cnt = (word.match(/[aeiou]/gi) || []).length;
if (cnt == 3){
if (hasDoubleVowels(word)){
// words like "piece, fleece, grease"
response.push(word);
isSpecialCase = true;
}
}
if (cnt == 2){
// words like "phase, phrase, blaze, name",
if (hasRecurringConsonant(word) == false) {
// but not like "syllable"
response.push(word);
isSpecialCase = true;
}
}
}
}
if (isSpecialCase == false){
const syllableRegex = /[^aeiouy]*[aeiouy]+(?:[^aeiouy]*$|[^aeiouy](?=[^aeiouy]))?/gi;
response = word.match(syllableRegex);
}
return response;
}

Fetching function name and body code from JavaScript file using C#

I need to fetch particular function and its body as a text from the javascript file and print that function as an output using C#. I need to give function name and js file as an input parameter. I tried using regex but couldnt achieved the desired result. Here is the code of regex.
public void getFunction(string jstext, string functionname)
{
Regex regex = new Regex(#"function\s+" + functionname + #"\s*\(.*\)\s*\{");
Match match = regex.Match(jstext);
}
Is there any other way I can do this?
This answer is based on the assumption which you provide in comments, that the C# function needs only to find function declarations, and not any form of function expressions.
As I point out in comments, javascript is too complex to be efficiently expressed in a regular expression. The only way to know you've reached the end of the function is when the brackets all match up, and given that, you still need to take escape characters, comments, and strings into account.
The only way I can think of to achieve this, is to actually iterate through every single character, from the start of your function body, until the brackets match up, and keep track of anything odd that comes along.
Such a solution is never going to be very pretty. I've pieced together an example of how it might work, but knowing how javascript is riddled with little quirks and pitfalls, I am convinced there are many corner cases not considered here. I'm also sure it could be made a bit tidier.
From my first experiments, the following should handle escape characters, multi- and single line comments, strings that are delimited by ", ' or `, and regular expressions (i.e. delimited by /).
This should get you pretty far, although I'm intrigued to see what exceptions people can come up with in comments:
private static string GetFunction(string jstext, string functionname) {
var start = Regex.Match(jstext, #"function\s+" + functionname + #"\s*\([^)]*\)\s*{");
if(!start.Success) {
throw new Exception("Function not found: " + functionname);
}
StringBuilder sb = new StringBuilder(start.Value);
jstext = jstext.Substring(start.Index + start.Value.Length);
var brackets = 1;
var i = 0;
var delimiters = "`/'\"";
string currentDelimiter = null;
var isEscape = false;
var isComment = false;
var isMultilineComment = false;
while(brackets > 0 && i < jstext.Length) {
var c = jstext[i].ToString();
var wasEscape = isEscape;
if(isComment || !isEscape)
{
if(c == #"\") {
// Found escape symbol.
isEscape = true;
} else if(i > 0 && !isComment && (c == "*" || c == "/") && jstext[i-1] == '/') {
// Found start of a comment block
isComment = true;
isMultilineComment = c == "*";
} else if(c == "\n" && isComment && !isMultilineComment) {
// Found termination of singline line comment
isComment = false;
} else if(isMultilineComment && c == "/" && jstext[i-1] == '*') {
// Found termination of multiline comment
isComment = false;
isMultilineComment = false;
} else if(delimiters.Contains(c)) {
// Found a string or regex delimiter
currentDelimiter = (currentDelimiter == c) ? null : currentDelimiter ?? c;
}
// The current symbol doesn't appear to be commented out, escaped or in a string
// If it is a bracket, we should treat it as one
if(currentDelimiter == null && !isComment) {
if(c == "{") {
brackets++;
}
if(c == "}") {
brackets--;
}
}
}
sb.Append(c);
i++;
if(wasEscape) isEscape = false;
}
return sb.ToString();
}
Demo

How can I check that a string does not include the text of another string?

I have this javascript code:
if (fromState.name == "home.subjects.subject.exams.exam.tests.test" &&
toState.name == "home.subjects.subject.exams.exam.tests") {
tes.test.current = false;
tes.test = null;
}
I understand that I can do a simple match here:
toState.name == "home.subjects.subject.exams.exam.tests"
To check the toState name.
But how could I check the toState.name does not include the string:
"home.subjects.subject.exams.exam.tests" ?
for example the toStateName could be:
"home" or "home.access" or "home.city"
ES6 version of this is (check out answer from Allison):
!str1.includes(str2)
The original accepted answer was:
You are looking for indexOf
var x = "home.subjects.subject.exams.exam.tests";
console.log(x.indexOf('subjects')); // Prints 5
console.log(x.indexOf('state')); // Prints -1
You could use includes and negate it.
!str1.includes(str2)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
var include_flag = toState.name.includes("home.subjects.subject.exams.exam.tests");
return !include_flag;
Using the JS includes method would probably be your best bet. I get I'm a little late in answering this question, but I was just googling this myself and came up with this answer after some fiddling with the code. This code will return true if toState.name does NOT include the string given.
Hope this helps anyone searching the same question I had!
But how could I check the toState.name does not include the string:
var strArr = "home.subjects.subject.exams.exam.tests.test".split(".");
var name = "home.subjects.subject.exams.exam.tests";
var contains = false;
strArr.reduce( function(prev, current){
if ( name.indexOf( current ) != -1 )
{
contains = true;
}
return prev + "." + current;
} );
if (contains)
{
alert( "yes it contains" );
}
else
{
alert( "Nope" );
}
The original question contained a "?" ternary operator, so here is how to do it using a ternary operator.
Suppose you're writing a poker game and have a rainbow flop. Now suppose you want the missing suit from the flop.
let flop = "3h Js 9c";
let missingSuit = !flop.includes("c") ? "c" :
!flop.includes("d") ? "d" :
!flop.includes("h") ? "h" : "s";
// missingSuit equals "d"
For me jQuery Version is 1.10.2
To check the substring within the string you can use includes jQuery function like this
var sub_str = "find"
var main_str = "find me if you can"
result = main_str.includes(sub_str)
if result{
* Stuff todo if result found
}else{
* Stuff todo if result not found
}
result true; // if you have sub string finder method separately and calling it from somewhere else.

How to check if the elements of an array are identical in javascript (more than 2 elements)

I am trying to make sure that a phone# is not all identical characters, example 1111111111
The code I am using works but there has to be a cleaner way. I've tried loops but that only compares two consecutive characters at a time. This is what I am using now:
if (MainPhone.value != "")
{
if ((MainPhone.value == 1111111111) || (MainPhone.value == 2222222222) || (MainPhone.value == 3333333333) || (MainPhone.value == 4444444444) || (MainPhone.value == 5555555555) || (MainPhone.value == 6666666666) || (MainPhone.value == 7777777777) || (MainPhone.value == 8888888888) || (MainPhone.value == 9999999999) || (MainPhone.value == 0000000000))
{
window.alert("Phone Number is Invalid");
MainPhone.focus();
return false;
}
}
I found this recommendation for someone else' question but could not get it to work.
var dup = MainPhone.value.split('');
if all(dup == dup(1))
I would try something like this:
var phone = '11111211';
var digits = phone.split('').sort();
var test = digits[0] == digits[digits.length - 1];
Simply sort the array and compare first and last element..
You can use a regular expression like this to check if all characters are the same:
^(.)\1*$
Example:
var phone = '11111111';
if (/^(.)\1*$/.test(phone)) {
alert('All the same.');
}
Demo: http://jsfiddle.net/Guffa/3V5en/
Explanation of the regular expression:
^ = matches start of the string
(.) = captures one character
\1 = matches the first capture
* = zero or more times
$ = matches end of the string
So, it captures the first character, and matches the rest of the characters if they are the same.

C# String.IsNullOrEmpty Javascript equivalent

I want to try to do string call equivalent to the C# String.IsNullOrEmpty(string) in javascript. I looked online assuming that there was a simple call to make, but I could not find one.
For now I am using a if(string === "" || string === null) statement to cover it, but I would rather use a predefined method (I keep getting some instances that slip by for some reason)
What is the closest javascript (or jquery if then have one) call that would be equal?
You're overthinking. Null and empty string are both falsey values in JavaScript.
if(!theString) {
alert("the string is null or empty");
}
Falsey:
false
null
undefined
The empty string ''
The number 0
The number NaN
If, for whatever reason, you wanted to test only null and empty, you could do:
function isNullOrEmpty( s )
{
return ( s == null || s === "" );
}
Note: This will also catch undefined as #Raynos mentioned in the comments.
if (!string) {
// is emtpy
}
What is the best way to test for an empty string with jquery-out-of-the-box?
If you know that string is not numeric, this will work:
if (!string) {
.
.
.
You can create one Utility method which can be reused in many places such as:
function isNullOrEmpty(str){
var returnValue = false;
if ( !str
|| str == null
|| str === 'null'
|| str === ''
|| str === '{}'
|| str === 'undefined'
|| str.length === 0 ) {
returnValue = true;
}
return returnValue;
}
you can just do
if(!string)
{
//...
}
This will check string for undefined, null, and empty string.
To be clear, if(!theString){//...} where theString is an undeclared variable will throw an undefined error, not find it true. On the other hand if you have: if(!window.theString){//...} or var theString; if(!theString){//...} it will work as expected. In the case where a variable may not be declared (as opposed to being a property or simply not set), you need to use: if(typeof theString === 'undefined'){//...}
My preference is to create a prototype function that wraps it up for you.
Since the answer that is marked as correct contains a small error, here is my best try at coming up with a solution. I have two options, one that takes a string, the other takes a string or a number, since I assume many people are mixing strings and numbers in javascript.
Steps:
-If the object is null it is a null or empty string.
-If the type is not string (or number) it's string value is null or empty. NOTE: we might throw an exception here as well, depending on preferences.
-If the trimmed string value has a length that is small than 1 it is null or empty.
var stringIsNullOrEmpty = function(theString)
{
return theString == null || typeof theString != "string" || theString.trim().length < 1;
}
var stringableIsNullOrEmpty = function(theString)
{
if(theString == null) return true;
var type = typeof theString;
if(type != "string" && type != "number") return true;
return theString.toString().trim().length < 1;
}
you can say it by logic
Let say you have a variable name a strVal, to check if is null or empty
if (typeof (strVal) == 'string' && strVal.length > 0)
{
// is has a value and it is not null :)
}
else
{
//it is null or empty :(
}

Categories

Resources