This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 9 years ago.
I'd like to achieve that, if "clientpsseabq" string is contained in variable Var_words then equal true, else false. I just have no idea what method or function do I need to use?
var Var_words = "https://www.go.me/outputsearchs/clientpsseabq"
if ( Var_words contains string "`clientpsseabq`"){
return true;
}else{
return false;
}
if someone could help me how can I complete this task?
Use the (native JavaScript) function String.indexOf():
if(Var_words.indexOf('clientpsseabq') !== -1) {
return true;
} else {
return false;
}
.indexOf() returns the index of the string. If the string is not found, it returns -1.
A smaller, cleaner solution would be to simply return the value of the conditional directly:
return (Var_words.indexOf('clientpsseabq') !== -1);
You can try this
if (Var_words.indexOf("clientpsseabq") >= 0)
or with care of case sensitivity
if (Var_words.toLowerCase().indexOf("clientpsseabq") >= 0)
{
// your code
}
use a regular expression to test for the case
if(/clientpsseabq/.test(Var_words)){
//given string exists
} else {
//given string does not exists
}
if(Var_words.indexOf("clientpsseabq") >= 0))
{
}
Related
This question already has answers here:
How to do case insensitive string comparison?
(23 answers)
Closed 2 years ago.
I understand we need to use toUpperCase, but I wasn't sure where to put it. I would like the word "toyota" to be acceptable whether it's uppercase or lowercase.
let correctGuess = false;
let car = "toyota";
let guess = prompt ('guess the car');
if (guess === car){
correctGuess = true;
}
if (correctGuess === true){
console.log ('correct');
}
else {
console.log('incorrect')
}
Convert both of them to either uppercase or lowercase and compare.
Example:
if(guess.toLowerCase() === car.toLowerCase()) {
// your logic
}
Although you have already defined car as lowercase so you don't really need to convert it to lowercase.
Change
if (guess === car){
correctGuess = true;
}
To
if (guess.toUpperCase() === car.toUpperCase()){
correctGuess = true;
}
Kind of redundant but it gets useful if the car variable itself was taken from a user input.
You can also make both .toLowerCase to get the same result, literally no difference
This question already has answers here:
How to count string occurrence in string?
(40 answers)
Closed 2 years ago.
I tried to solve the following problem without using the for loop:
"Write a function countBs that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters there are in the string.
console.log(countBs("BBC")); // → 2
Thank you for your help.
Here is the code I wrote so far which doesn't work:
function countBs(word) {
let count = 0
if (word.length == 0) {
return count;
} else {
if (word[word.length - 1] == 'B') {
count++
}
return countBs(word.slice(0, word.length - 1))
}
}
console.log(countBs("BBC"))
You can easily use regex for this case:
function countBs(word) {
const matches = word.match(/B/g);
return matches && matches.length || 0;
}
Basically it globally searches for occurrences of 'B'. If it find it, it returns the length of it, if the matches are null it will return 0.
Simpler less expressive:
function countBs(word) {
return (word.match(/B/g) || []).length;
}
This question already has answers here:
Java, Check if a String is a palindrome. Case insensitive
(5 answers)
Closed 5 years ago.
I am asked to check if a string is a Palindrome.
To not be case sensitive. To ignore all characters that are not letters.
My Answer
function palindrome(str) {
var oldStr = str.toLowerCase().replace(/\s+|\,|\.|\_|\-|\:|\(|\)|\/|\\/g, '');
var newStr = str.replace(/\s+|\,|\.|\_|\-|\:|\(|\)|\/|\\/g, '').split("").reverse().join("").toLowerCase();
if ( oldStr === newStr){
return true;
}
else {
return false;
}
}
palindrome("ininiNI");
The function is to be checked with any string possibility.
Example: ("0_0 (: /-\ :) 0-0") Which according to the requirements should return true.
I could not find a better solution in JavaScript then the one above.
Is there a faster/better way than just writing out each possible character to be removed/replaced? (especially since what I wrote is far from exhaustive...)
There is no need to call toLowerCase() and replace() twice. You can also cut string in a half, reverse one part and then compare. That way you can speed up your function few times at least.
Optimized function may look like that:
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-z]/g, '');
var max = str.length - 1;
for (var i = Math.floor(max / 2); i >= 0; i--) {
if (str[i] != str[max - i]) {
return false;
}
}
return true;
}
palindrome("inabcbani"); //true
palindrome("abcddcba"); //true
palindrome("a*#$(b)&^#%#%(*a"); //true
palindrome("abba"); //true
palindrome("abcdba"); //false
For loop will be the fastest way in my opinion as it's quick and simple. You can return false once you find first character that doesn't match.
How can I simply check if string can be converted to integer?
And I mean only integer, so string like '10.1' would not be converted to 10.
For example if I do:
parseInt('10.1', 10)
It returns 10
Is there something equivalent like it is in Python, so I would not need to do lots of checks?
In Python if I do int('10.1'), it gives me error, but if string is actually integer, only then it lets you convert it like int('10'). So it is very easy to check that without even using regex or some additional checks.
I tried this:
function isInteger (value) {
if ($.isNumeric(value) && Number(value) % 1 === 0){
return true;
} else {
return false;
}
}
It kinda works, but if I write for example 10., it will return true, because Number converts to 10. I guess I need to use regex to check such thing?
P.S. I searched for this question, but all answers seem to be vague and actually does not answer how to properly check for integer (not just if it is number).
One possibility is to use a regex to test, like so:
function isInteger(value) {
return /^\d+$/.test(value);
}
If i understand your question correctly then this should do it:
function isInteger(value) {
if(parseInt(value,10).toString()===value) {
return true
}
return false;
}
It converts a string to an integer and then back to a string and compares that to the original string. If they match, then it returns true, else it returns false.
You can use
Number function of js (http://www.w3schools.com/jsref/jsref_number.asp)
or
parseInt function of js (http://www.w3schools.com/jsref/jsref_parseint.asp)
You can use regex to detect if it match any value.
function isInterger(value) {
if (value.match(/^\d+$/) {
return true;
} else {
return false;
}
}
https://regex101.com/r/lE5tK1/1
This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 9 years ago.
I have this function
function validateUsername(str,minL,maxL){// i'm passing validateUsername("asdf_1",2,8)
var exp=new RegExp(/^[a-z0-9_-]\w{"+minL+","+maxL+"}$/);
switch(exp.test(str)){
case true: return true;
case false: return false;
}
}
I want to insert minimum Length and maximum length dynamically,
But if above code used,its giving me false whether it should accept the string as true.
can anyone tell me, what should i use rather "+variable+" to insert the value dynamically.
Thanks in advance.
You can use the regex object constructor to build your regex from a string as stated here.
Example taken from linked answer :
var re = new RegExp("a|b", "i");
// same as
var re = /a|b/i;
In your case that would do something like :
function validateUsername(str,minL,maxL){// i'm passing validateUsername("asdf_1",2,8)
var exp=new RegExp("^[a-z0-9_-]\w{" + minL + "," + maxL + "}$");
/*
why ???
switch(exp.test(str)){
case true: return true;
case false: return false;
}
*/
return exp.test(str);
}
You can separate length validation from the pattern, something like this
if(str.length<minL || str.length>maxL){
// invalid length
}else{
var exp=new RegExp(/^[a-z0-9_-]\w$/);
return exp.test(str)
}