Javascript, string, RegEx, if and else if, console.log different output - javascript

I want to output a string's vowels in order, so I decided to use RegEx to do it.
However, when I put the expression in different position in (if and else if), the output is different for the same expression. Could anyone explain?
function ordered_vowel_word(str) {
if(str.match(/[aeiou]{1,}/g) !== ""){
var arr = str.match(/[aeiou]{1,}/g);
console.log(arr);
}
else
console.log(str);
}
ordered_vowel_word("bcg");
ordered_vowel_word("eebbscao");
/* The Output */
ordered_vowel_word("bcg");
==> null
ordered_vowel_word("eebbscao");
==> ["ee", "ao"]
But if I restructure the expression,
function ordered_vowel_word(str) {
if(str.match(/[^aeiou]/) !== "")
console.log(str);
else if(str.match(/[aeiou]{1,}/g) !== ""){
var arr = str.match(/[aeiou]{1,}/g);
console.log(arr);
}
}
The output will be
ordered_vowel_word("bcg");
==> bgv
ordered_vowel_word("eebbscao");
==> eebbscao

Take note that string.match returns an array if there is at least one match, and it returns null if there is no match.
What I think you want is :
if(str.match(/[aeiou]{1,}/g) == null){ // no matches
or
if(str.match(/[aeiou]{1,}/g) != null){ //has a match
As for the sorting, you have to do process the array you get with str.match.
Check out this SO answer for sorting arrays. Yes, you can use > and < operators for characters.

The return value of str.match the way you are using it is an array containing the matches when it matches. Also, it is not an empty string when there are no matches... it is actually null.
Try changing what you are testing for in your if condition to this:
str.match(/[aeiou]{1,}/g) !== null)

Related

indexOf with Nothing Before String

I have a string which contains the following:
string = "GOAT,Speed,OCG GOAT";
I then have the following:
if(data.format.indexOf("GOAT") >= 0){
}
if(data.format.indexOf("OCG GOAT") >= 0){
}
Both of them naturally return as TRUE because "GOAT" is contained in both of them.
Is it possible to do an indexOf where nothing comes before the string so I can do only a check on "GOAT" and not have "OCG GOAT" return true? Because "GOAT" will always come first in the string.
Either check that the indexOf is equal to 0 (indicating that the substring you're searching for occurs at the very beginning of the haystack):
data.format.indexOf('GOAT') === 0
Or use startsWith instead:
data.format.startsWith('Goat')
Using regular expressions could be a solution, too:
const GOAT_REGEX = /^GOAT.*/g;
const SUCCESS = "GOAT,Speed,OCG GOAT";
const FAILURE = "Speed,OCG GOAT";
console.log('Should work (true is correct)', GOAT_REGEX.test(SUCCESS));
console.log('Should fail (false is correct)', GOAT_REGEX.test(FAILURE));

How do I check for brackets in a specific place in the string?

I have this code and it needs to returns true or false based on the string you give it.
This is the only example on which it doesn't work. How can I check if brackets exist in a specific index of the string?
function telephoneCheck(str) {
var newStr = str.replace(/-/g,'').replace(/ /g,'').replace(/\(|\)/g,'');
var valid = true;
var re = /\([^()]*\)/g;
while (str.match(re))
str = str.replace(re, '');
if (str.match(/[()]/)){
valid = false;
}
if(newStr.length === 10 && valid === true && str.indexOf()){
return true;
}else if(newStr.length === 11 && str[0] != "-" && newStr[0] == 1 && valid === true){
return true;
}else{
return false;
}
}
telephoneCheck("(6505552368)");
Based on your code I think you might be looking for something like this:
'(6505552368)'.replace(/^\((\d+)\)$/, '$1');
The ^ and $ in the RegExp will match the start and the end of the string. The \d+ will match one or more numbers. The extra parentheses form a capture group that is then used in the replacement as $1.
You might be better off doing more work using RegExps rather than doing all that replacing but without knowing the exact requirements it's difficult to be more precise. I highly suggest learning more about RegExp syntax.
If you literally just want to know whether 'brackets exist in a specific index' then you can just use:
str.charAt(index) === '(';
To check if there are brackets at a specific index in the string:
/[()]/.test(str[index])
To check if there are any brackets in the string at all:
/[()]/.test(str)
If you want to test for a specific bracket type (e.g. opening but not closing) remove the other one (e.g. closing) from the regex.

Understanding the palindrome code with the logic of split and reverse

I am trying to write a palindrome code, so I am using the split and reverse methods. Is my below logic correct? Can I directly use the reverse method instead of giving split and then reverse?
If I give == it prints palindrome where as if I give === it prints not palindrome. I am a beginner in JS and I am trying to learn.
var actualWord = "madam"
var splittedWord = actualWord.split();
console.log("splittedWord---->" + splittedWord);
var reversedWord = splittedWord.reverse();
console.log("reversedWord---->" + reversedWord);
console.log("boolean" + reversedWord === actualWord);
if (reversedWord === actualWord) {
console.log("palindrome");
} else {
console.log("not palindrome")
}
Your logic is flawed as split() with no parameter to split by returns the original word, which then means that reverse() has no effect as you're working on a single element array. You are also attempting to check arrays for equality, which will not work.
To do what you require you need to split by '' to generate a character array which you can then reverse() and join() back together to invert the characters of the word. Then you can compare the words to discover if the original was a palindrome. Try this:
var actualWord = "madam"
var reverseWord = actualWord.split('').reverse().join('');
console.log(actualWord, reverseWord);
if (actualWord === reverseWord) {
console.log(actualWord + " IS a palindrome");
} else {
console.log(actualWord + " IS NOT a palindrome")
}
Working example
Taking this a step further you could extract the logic to it's own function and make the string comparison case-insensitive:
console.log('madam', isPalindrome('madam'));
console.log('madame', isPalindrome('madame'));
console.log('raceCAR', isPalindrome('raceCAR'));
function isPalindrome(word) {
var reverseWord = word.split('').reverse().join('');
return word.toLowerCase() === reverseWord.toLowerCase();
}
Example fiddle
Several things needed to make your code correct:
Split the words using .split("") not .split()
Create strings from the arrays using .join("")
Put parentheses around the comparator in your "boolean" line, otherwise the "+" will be performed before the "==="
var actualWord = "madam";
var splittedWord = actualWord.split("");
log("splittedWord---->" + splittedWord.join(""));
var reversedWord = splittedWord.reverse();
log("reversedWord---->" + reversedWord.join(""));
log("boolean---->" + (reversedWord.join("") === actualWord));
if (reversedWord.join("") === actualWord) {
log("palindrome");
} else {
log("not palindrome")
}
function log(str) {
document.body.appendChild(document.createElement("p")).innerHTML = str;
}
The == operator will compare for equality after doing any necessary
type conversions. The === operator will not do the conversion, so if
two values are not the same type === will simply return false. It's
this case where === will be faster, and may return a different result
than ==. In all other cases performance will be the same.
e.g.-
"1" == 1
true
"1" === 1
false
in your case, reversedWord is an array but actualWord is string, hence you get false when using ===, but when you use == JS does the necessary type conversion for you and you get true.
You have to call the split function before the reverse function because you are referring to a string and not an array.

Javascript - search a string from beginning

Hello i currently have this part of the code that i developed but i want to do some edits:
$('#target').keydown(function(event) {
if (event.which == 13)
{
var users = ["Dennis Lucky","Lucy Foo","Name Lastname","Billy Jean"];
var match = 0;
var str = $('#target').val();
for(i=0;i<users.length;i++)
{
if ( users[i].toLowerCase().indexOf(str.toLowerCase()) > -1 )
{
match++;
name = users[i];
}
}
if(match == 1)
{
$('#target').val('');
$('#chatbox').append('<span style="color:blue;">'+name+'</span> ');
console.log(name);
}
else if (match >= 2)
{
console.log("many entries");
}
}});
The idea is that if i type something and hit enter if the partial string exists in users becomes blue color.With this code i have the problem that if i write "Lu" i get 2 results, "Dennis Lucky" and "Lucy Foo".
I want to change my code so when i type "Lu" it will start searching the words starting with this sting and not include it.
if ( users[i].toLowerCase().indexOf(str.toLowerCase()) > -1 )
The condition is true if indexOf's returned value is greater than -1. In JavaScript, indexOf returns -1 if a match "needle" (the string you're searching for) isn't found in your "haystack" (the string that you're searching within). Otherwise, it returns the first index of the "needle" in your "haystack".
To explain my terminology of indexOf, here's an example:
haystack.indexOf(needle); // How to use the indexOf function
console.log("apples oranges apples".indexOf("apples")); // This would print 0.
console.log("apples oranges apples".indexOf("white")); // This would print -1.
If you want to ensure that the string starts with the "needle", you simply need to change your code to
if ( users[i].toLowerCase().indexOf(str.toLowerCase()) == 0 )
If you want your "words" ("Lucy Foo" would be "Lucy" and "Foo"), either split your name strings by a space character and perform the indexof search with the elements of the resultant array, or turn to regex.
It is better to use regexes. Since you want to search the start of string use ^
Refer Regular Expressions documentation on MDN for more information.

Javascript match part of url, if statement based on result

Here is an example of the url i'm trying to match: http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx
What im trying to match is http: //store.mywebsite.com/folder-1 except that "folder-1" will always be a different value. I can't figure out how to write an if statement for this:
Example (pseudo-code)
if(url contains http://store.mywebsite.com/folder-1)
do this
else if (url contains http://store.mywebsite.com/folder-2)
do something else
etc
In the interest of keeping things very simple...
if(location.pathname.indexOf("folder-1") != -1)
{
//do things for "folder-1"
}
this might give you false positives if the value "folder-1" could be present in other parts of the string. If you are already making sure this is not the case, the provided example should be sufficient.
I would split() the string and check an individual component of the url:
var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"
// split the string into an array of parts
var spl = str.split("/");
// spl is now [ http:,,store.mywebsite.com,folder-1,folder-2,item3423434.aspx ]
if (spl[4] == "folder-1") {
// do something
} else if (spl[4] == "folder-2") {
// do something else
}
Using this method it's easy to check other parts of the URL too, without having to use a regular expression with sub-expression captures. e.g. matching the second directory in the path would be if spl[5] == "folder-x".
Of course, you could also use indexOf(), which will return the position of a substring match within a string, but this method is not quite as dynamic and it's not very efficient/easy to read if there are going to be a lot of else conditions:
var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"
if (str.indexOf("http://store.mywebsite.com/folder-1") === 0) {
// do something
} else if (str.indexOf("http://store.mywebsite.com/folder-2") === 0) {
// do something
}
Assuming the base URL is fixed and the folder numbers can be very large then this code should work:
var url = 'http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx'
, regex = /^http:..store.mywebsite.com.(folder-\d+)/
, match = url.match(regex);
if (match) {
if (match[1] == 'folder-1') {
// Do this
} else if (match[1] == 'folder-2') {
// Do something else
}
}
Just use URL parting in JS and then you can match URL's against simple string conditions or against regular expressions

Categories