Check if string is starting with prefix - javascript

I would like to check with javascript if array items starts with the word "prefix".
So far I've done something like this:
let array = ["prefix-word1", "prefix-word2"];
array.forEach(function(element) {
if (element.lastIndexOf('prefix', 0) == 0) {
console.log('prefix');
}
}
For some reason I keep get an error that prefix is not defined. Please help.

This one works (check the comments on the code):
let array = ["prefix-word1", "prefix-word2" , "does not start with prefix"];
array.forEach(function(element) {
// Check if the first word is prefix
if (element.indexOf('prefix') == 0) {
console.log('prefix');
console.log(element);
}
});
console.log("Second approach which is not suggested");
array.forEach(function(element) {
// not the correct approach as suggested by #Barmar though it works
if (element.lastIndexOf('prefix',0) == 0) {
console.log('prefix');
console.log(element);
}
});

Try using double quotation marks instead of single like this "prefix" in functions.

Related

Run action if contains part of an attr value

I have a input with this
attr('data-disabled-dates','12/02/2022; 13/02/2022; 14/02/2022; 15/02/2022; 10/03/2022; 11/03/2022; 16/02/2022')
And a const which results in tomorrow dynamically, so for this case the result is "16/02/2022"
Now i want to run action if it matches that tomorrow's date is within the attr data-disabled-dates.
So i tried this
if (jQuery(input).attr('data-disabled-dates') == '16/02/2022')
{ console.log('work') } else {
console.log ('not') }
But it only gives me true if the whole sequence is exactly the same, that is, if I put "12/02/2022; 13/02/2022..." if it will give the result, but I only want it to be true if the value I am putting is inside
You can use String.includes() or String.split('; ') to convert string to array and check if it includes the desired value.
if (jQuery(input).attr('data-disabled-dates').includes('16/02/2022')) {
console.log('work')
} else {
console.log('not')
}
Working example in vanilla JS
const div = document.querySelector('#data');
const dates = div.getAttribute('data-disabled-dates');
if (dates.includes('16/02/2022')) {
console.log('work')
} else {
console.log('not')
}
// or
if (dates.split('; ').includes('16/02/2022')) {
console.log('work')
} else {
console.log('not')
}
<div id="data" data-disabled-dates="12/02/2022; 13/02/2022; 14/02/2022; 15/02/2022; 10/03/2022; 11/03/2022; 16/02/2022" />
btw https://youmightnotneedjquery.com/
== performs exact string matches, not substring matches.
You can use .split() to split the attribute value into an array, then use .includes() to test if the array contains the date.
if (jQuery(input).data('disabled-dates').split('; ').includes('16/02/2022')) {
console.log("work");
} else {
console.log("not");
}
You can use indexOf to be greater than 0. IndexOf if you need to support IE.
var dataAttrValue = jQuery(input).attr('data-disabled-dates');
var date = '16/02/2022';
if (typeof dataAttrValue !== 'undefined' && dataAttrValue.indexOf(date)) > 0) { console.log('work');
} else {
console.log ('not');
}
OR
jQuery(input).is(“[data-disabled-dates*='16/02/2022']”);
But I suggest using JQuery Data to store and retrieve values from elements.

How can I use a for loop to delete empty spaces at the left and right of a string in JavaScript?

I'm trying to make a homemade trim()'s JavaScript method. I mean, what I want to do can be achieved using trim(): to delete all white spaces from the left and right of the string.
I came up with this cumbersome solution; I think it should work, but it's not working at all; instead, it is removing all elements of the string array and leaving just an array of strings with one empty space as the unique element.
Here is a running snippet of the code I did:
const stringWithManyWhiteSpaces = ' I like ants... Remember us ';
const charArray = [...stringWithManyWhiteSpaces];
function killLeftToRight(charArr) {
for ( let i = 0; i < charArr.length; i++) {
if (charArr[i] === ' ') {
charArr.splice(i + 1);
} else {
break;
}
}
}
function killRightToLeft(charArr) {
for ( let i = charArr.length -1; i >= 0; i--) {
if (charArr[i] === ' ') {
charArr.splice(i + 1);
} else {
break;
}
}
}
function myTrim(){
killRightToLeft(charArray)
killLeftToRight(charArray);
console.log(charArray)
}
myTrim();
May anyone let me figure out what's wrong with my code? Thank you so much.
To remove items from an array, splice requires you to specify how many to remove, in the second argument
splice will remove the item at the given index from the array, so on the next iteration, if you're iterating through indicies in ascending order, you may "skip" an item, due to its index having just been re-calculated
Easier to use .pop (remove from end) and .shift (remove from beginning).
const stringWithManyWhiteSpaces = ' I like ants... Remember us ';
function killLeftToRight(charArr) {
while (charArr[0] === ' ') {
charArr.shift();
}
}
function killRightToLeft(charArr) {
while (charArr[charArr.length - 1] === ' ') {
charArr.pop();
}
}
function myTrim(str){
const charArray = [...str];
killRightToLeft(charArray);
killLeftToRight(charArray);
console.log(charArray.join(''));
}
myTrim(stringWithManyWhiteSpaces);
your approach can be changed in different ways so it would work fine as mentioned in the previous answer, but if your target is to have your own implementation for trimming, what about implementing it in a simpler way?:
const stringWithManyWhiteSpaces = `
I like ants... Remember us
`;
function trimMe(stringToTrim) {
return stringToTrim.replace(/^[\s\n]+|[\s\n]+$/g, '')
}
console.log(trimMe(stringWithManyWhiteSpaces));
all you need for remove white space is
string.trim()

How to find whole substring in string?

I have a string and I have to check if that string contains defined substring I need to do some work and otherwise, I should return some error.
I have the following code:
function isContains(myString) {
let subString = 'test1234';
if(myString.includes(subString)) {
// to do some work
} else {
// return some error.
}
}
but the problem is if myString = 'my-string-test1-rrr' its condition return true.
How can I get true only in case when the whole subString was included in myString?
Use indexOf() instead.
function isContains(myString) {
let subString = 'test1234';
if(myString.indexOf(subString) > -1) {
// to do some work
} else {
// return some error.
}
}
you can use regex to check if that value is present are not;
example 1
without containing the specific string
var test = 'my-string-test1-rrr';
console.log(' test --- ', test.match(/test1234/g))
example 2
contains the specific string
var test = 'my-string-test1234-rrr';
console.log(' test --- ', test.match(/test1234/g))
It is highly recommended to use includes() over indexOf() and further indexOf returns the index of the occurrence where you would prefer an immediate answer - false / true if that substring is found inside the searched string.
Your function does exactly what you are asking. I would suggest to isolate the retrieval of this function and make it purer like so, then when you have the return boolean value you could utilize it after to run whatever logic you wish. This way you keep this function pure and separate your concerns better.
I also believe it would be easier for you to debug your issue if you isolate this functions like In the example I provided.
function isContains(myString) {
let subString = 'test1234';
let isContains = false;
if(myString.includes(subString)) {
isContains = true;
} else {
isContains = false;
}
return isContains;
}
You could use it like so in a later phase in your code:
const myString = 'my-string-test1-rrr';
let shouldRunOtherLogic = isContains(myString);
if (shouldRunOtherLogic) {
// to do some work
} else {
// return some error.
}
Hope I could help, if there's anything further you may need feel free to let me know.

How to find the missing next character in the array?

I have an array of characters like this:
['a','b','c','d','f']
['O','Q','R','S']
If we see that, there is one letter is missing from each of the arrays. First one has e missing and the second one has P missing. Care to be taken for the case of the character as well. So, if I have a huge Object which has all the letters in order, and check them for the next ones, and compare?
I am totally confused on what approach to follow! This is what I have got till now:
var chars = ("abcdefghijklmnopqrstuvwxyz"+"abcdefghijklmnopqrstuvwxyz".toUpperCase()).split("");
So this gives me with:
["a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
Which is awesome. Now my question is, how do I like check for the missing character in the range? Some kind of forward lookup?
I tried something like this:
Find the indexOf starting value in the source array.
Compare it with each of them.
If the comparison failed, return the one from the original array?
I think that a much better way is to check for each element in your array if the next element is the next char:
function checkMissingChar(ar) {
for (var i = 1; i < ar.length; i++) {
if (ar[i].charCodeAt(0) == ar[i-1].charCodeAt(0)+1) {
// console.log('all good');
} else {
return String.fromCharCode(ar[i-1].charCodeAt(0)+1);
}
}
return true;
}
var a = ['a','b','c','d','f']
var b = ['O','Q','R','S']
console.log(checkMissingChar(a));
console.log(checkMissingChar(b));
Not that I start to check the array with the second item because I compare it to the item before (the first in the Array).
Forward Look-Ahead or Negative Look-Ahead: Well, my solution would be some kind of that. So, if you see this, what I would do is, I'll keep track of them using the Character's Code using charCodeAt, instead of the array.
function findMissingLetter(array) {
var ords = array.map(function (v) {
return v.charCodeAt(0);
});
var prevOrd = "p";
for (var i = 0; i < ords.length; i++) {
if (prevOrd == "p") {
prevOrd = ords[i];
continue;
}
if (prevOrd + 1 != ords[i]) {
return String.fromCharCode(ords[i] - 1);
}
prevOrd = ords[i];
}
}
console.log(findMissingLetter(['a','b','c','d','f']));
console.log(findMissingLetter(['O','Q','R','S']));
Since I come from a PHP background, I use some PHP related terms like ordinal, etc. In PHP, you can get the charCode using the ord().
As Dekel's answer is better than mine, I'll try to propose somewhat more better answer:
function findMissingLetter (ar) {
for (var i = 1; i < ar.length; i++) {
if (ar[i].charCodeAt(0) != ar[i-1].charCodeAt(0)+1) {
return String.fromCharCode(ar[i-1].charCodeAt(0)+1);
}
}
return true;
}
var a = ['a','b','c','d','f']
var b = ['O','Q','R','S']
console.log(findMissingLetter(a));
console.log(findMissingLetter(b));
Shorter and Sweet.

Javascript - check if string is part of a string in an array

I have an array which lists a couple of websites:
var validSites = new Array();
validSites[0] = "example_1.com";
validSites[1] = "example_2.com";
validSites[2] = "example_3.com";
now i have a small script which checks what web address you are on and could return something like this:
example_1.com/something/something_else
now i need to check if that address is one of the valid sites.
so
example_1.com/*ANYTHING*
would pass as correct.
but
exampleshmample.com
would pass as incorrect.
Now i know you can do an indexOf() which can check if a string is part of a string and it would return -1 if false. but how would i check it through the entire array?
P.s - its for a Chrome Extension.
thanks
Here’s an idea:
var str = 'example_1.com/something/something_else';
if( validSites.indexOf( str.split('/')[0] ) > -1 ) {
// is valid
}
Another one is to use regexp on a joined array:
var str = 'example_1.com/something/something_else';
new RegExp('^('+validSites.join('|')+')','i').test(str);
This will also match f.ex example_1.comyoyoyo
if (validStates.indexOf("example_1.com") > -1) {
// Then it's inside your array
}
else {
// Then it's not inside your array
}
I'd go with json notation, if you can switch from an array, in this scenario
var validSites = {
"example_1.com":"valid",
"example_2.com":true,
"example_3.com":1 //you could even start putting paths in here to beef up your check.
};
//..your check function would be:
.....
if(validSites[window.location.hostname]){
return true;
}else{
return false;
}
You can achieve this by looping and setting flag variable, Try this, i am not tested this.
Just i typed the code directly. i think this may help you
var flag =0;
var givenurl='example_1.com/*ANYTHING*';
for(int i=0 i<validSites.length;i++){
if(givenurl.indexOf(validSites[i])){
flag=1 //Found
}
}
if(flag) { //Url Found }else{ //not found }

Categories

Resources