if(string.Contains(string)). Is that possible? - javascript

I am trying to check if a string is contained in another string. Code behind is pretty straight forward. How can I do that in jquery?
function deleteRow(locName, locID) {
if(locName.Contains(locID)) {
alert("success");
}
}

Use String.prototype.indexOf
For example: (locName.indexOf(locID) > -1)
String.prototype.contains doesn't exist.

You can use the indexOf method of the string. If you really want the convenience of having a contains method, you could add one to String.prototype:
String.prototype.contains = function(str) {
return this.indexOf(str) > -1;
};
alert("foobar".contains("oob")); // true
alert("foobar".contains("baz")); // false

you can use indexOf if the string is found returned result will be different from -1
function deleteRow(locName, locID) {
if(locName.indexOf(locID) != -1) {
alert("success");
}
}
I hope this helps

Related

Not able to compare strings in Javascript

I am trying to compare a string with a set of strings stored in an array. Here is the block of code:
then(op => {
if (op[0].probability > FILTER_THRESHOLD) {
if (FILTER_LIST.indexOf(op[0].className) > 1) {
console.log("EUREKA! EUREKA! EUREKA!")
console.log(op[0].className)
return true;
}
}
return false;
})
The second if statement should evaluate to true in some cases but it is not. The return is always false.
op[0].className should be a string and I am also able to get the value from op[0].probability correctly.
What could be the reason?
I have tried debugging and cannot seem to get why the 'if' statement is not being true.
Here is the FILTER_LIST array:
var FILTER_LIST = ["Hello", "Please", "Simple"];
Please advise how I can fix this!
Thank you!
indexOf(...) > 1 asks "did it find a match at the third element or later?" You'll get false if it matched at index 0 or 1. If you want just "it found one anywhere", you want !== -1, >= 0, or to use includes instead of indexOf.
if (FILTER_LIST.indexOf(op[0].className) !== -1) {
// or
if (FILTER_LIST.indexOf(op[0].className) >= 0) {
// or
if (FILTER_LIST.includes(op[0].className)) {

Javascript Basic algorithm

Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array. No case-sensitivity and order doesn't matter only the letters matter. For ex - ["Hello","hello"] returns true and so does ["Alien","lien"] and also ["Mary", "Aarmy"]. I think you get it. If not return false.
I could solve it with Array.indexOf() === -1 (in the first for loop) but can it work with this code, it's the opposite. I just can't make it return false. Ultimately, I wanna know, can you make it return false without changing the method.
function mutation(arr) {
var split = arr[1].toLowerCase().split("");
var splitSecond = arr[0].toLowerCase().split("");
for(k=0;k<=arr[0].length;k++){
for(i=0;i<=arr[1].length;i++){
if(split[i]===splitSecond[k]) {
return true
}
}
} return false
}
mutation(["hello", "hney"], "");
If using any other method, explain :)
The problem with your code is that you return true; as soon as one letter matches.
What you need to do is check if all letters match, which is easier achieved by checking if any letter doesn't match.
mainloop:
for(k=0;k<=arr[0].length;k++){
for(i=0;i<=arr[1].length;i++){
if(split[i]===splitSecond[k]) {
continue mainloop; // found the letter, move on to next search
}
}
return false; // failed to find letter, fail here
}
return true; // haven't failed yet and end of input reached. Success!
Another alternative would be:
for(k=0;k<arr[0].length;k++) {
if( arr[1].indexOf(split[k]) < 0) {
// letter not found
return false;
}
}
// not failed yet? Excellent!
return true;
function mutation(arr) {
var test = arr[0].toLowerCase(),
chars = arr[1].toLowerCase(),
len=chars.length;
for(var i=0;i<len;i++)
if(test.indexOf(chars[i])==-1) //this char not exist in test string
return false;
return true;//all chars already checked
}
mutation(["hello", "he"]);
https://jsfiddle.net/hb2rsm2x/115/
Here is an interesting way using regular expressions. escapeRegExp was taken from here.
function mutation(arr){
var matcher = new RegExp('[^'+escapeRegExp(arr[1])+']', "i");
return arr[0].match(matcher) === null;
}
function escapeRegExp(s) {
return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
}

Javascript string index

I am currently working on some javascript on a website that helps companies see how their campaigns are doing on one collective screen. I am using an if statement to help separate some of the information but the when I go to check the code it says
String index out of range -1
Here is the sample code:
var place = {Media Buy Name};
if(place.indexof("Prospecting")){
return "Prospecting";
}
else if(place.indexof("AudienceTargeting")){
return "AudienceTargeting";
}
else if(place.indexof("Retargeting")){
return "Retargeting";
}
else{
return "Other";
}
1) Javascript is case-sensitive. So indexof is not the same as indexOf.
2) Your place variable is an object literal, so it has no methods except Object's ones unless you define a method manually yourself. Another option is making your variable an instance of Array or String which have indexOf method (1, 2).
So you have to either make your place variable an instance of Array/String or define indexOf method manually within place object. Then your code will work.
For if or else if condition indexOf function return int value so you have to compare it with.
If string found then return its index else return -1.
Check the following link:
http://www.w3schools.com/jsref/jsref_indexof.asp
var place = 'Prospecting'; // Can by dynamic
if(place.indexOf('Prospecting') > -1){
return 'Prospecting';
}
else if(place.indexOf('AudienceTargeting') > -1){
return 'AudienceTargeting';
}
else if(place.indexOf('Retargeting') > -1){
return 'Retargeting';
}
else{
return 'Other';
}

Handle result of multiple .search() arguments

As explained in How do you search multiple strings with the .search() Method?, you can use multiple arguments inside .search().
But how can I know which of the arguments given inside .search() returns a positive value?
E.g:
var search = string.search("hello|world|not");
if (search.positiveArgument == 1) {
//"hello" was found
} else if (search.positiveArgument == 2) {
//"world" was found
etc...
I am aware that .positiveArgument isn't valid, it is purely for example purposes.
Use .match() instead with a regular expression. The matched part will be returned.
For ex: "yo world".match(/hello|world|not/); returns ["world"]
var search = str.match(/hello|world|not/);
if (search && search.length === 1) {
if(search[0] == "hello") {
// hello was found
}
else if(search[0] == "world") {
// world was found
}
else {
// not was found
}
}

finding out if a text input includes a specific text with jquery

what is the best way of finding out if a text input includes a specific text with JQuery?
For example, how can I find out and return a Boolean result if $('#poo').val() includes airport?
EDIT
Here is the solution to my problem thanks to #Niklas;
var IsbtFortxtPropertyHotelNameOn = false;
$('#<%: txtPropertyHotelName.ClientID %>').keyup(function() {
if (/airport/i.test(this.value) && !IsbtFortxtPropertyHotelNameOn) {
$('#<%: txtPropertyHotelName.ClientID %>').btOn();
IsbtFortxtPropertyHotelNameOn = true;
} else if(IsbtFortxtPropertyHotelNameOn && !/airport/i.test(this.value)) {
$('#<%: txtPropertyHotelName.ClientID %>').btOff();
IsbtFortxtPropertyHotelNameOn = false;
}
});
If you want to have control over the case-sensitivity, you could use regex:
if (/airport/i.test(this.value)) alert('true');
It becomes especially useful if you need to check for multiple variables instead of just airport:
if (/(airport|station|docks)/i.test(this.value)) alert('true');
http://jsfiddle.net/niklasvh/tHLdD/
normally you'd do it with either indexOf or split functions, e.g.
$("#textInput").val().split("specifictext").length > 0
there's also Contains Selector:
Description: Select all elements that contain the specified text.
which serves a slightly different purpose but may be of use to you
if($("#elementId").val().indexOf("airport") != -1) {
//Contains "airport"
}
The JavaScript indexOf function returns the index of the first occurence of the specified string. If the string is not found, it returns -1.
Don't really know if it's the best way.. but
function findInpWithTxt(txt) {
var t = null;
$("input[type=text]").each(function() {
if ($(this).val().indexOf(txt) >= 0) {
t = this;
return false;
}
});
return t;
}
this will return the input if found, null if not

Categories