1

I've been doing research on testing if a value exists in an array, and keep getting matches for indexOf('textvalue').

But, my 'textvalue' will be a substring, and therefore won't pull a match. This is because I'm passing the field name to the method, and just need to delete the "Door: Front Left;" text by matching the array item on "Door". Does anyone know how I can accomplish this?

Here's the example code I'm working on:

(spnSelectedDisclosures will have a list of selected fields, and this is the code to remove the previous field selection from the text, which is semi-colon delimited.)

var currentText = $("#spnSelectedDisclosures").text();

var existingArr = currentText.split(";")

for (i=0;i < existingArr.length;i++) {

   var indexItem = " " + existingArr[i].toString(); // why is this still an object, instead of a string? Adding a space to it was a desperate try to make indexItem a string variable.

    if (indexItem.contains(substringText)) { // offending line, saying the object has no method 'contains'
       alert("there's been a match at: " + i);
       textToRemoveIndex = i;
       break;
    }
  }

 var textToRemove = existingArr[textToRemoveIndex];
 var newText = currentText.replace(textToRemove,""); 
 $("#spnSelectedDisclosures").text(newText); 

2 Answers 2

3

What's about this?

for (i=0;i < existingArr.length;i++) {
  if (existingArr[i].indexOf(substringText) > -1) { 
    alert("there's been a match at: " + i);
    textToRemoveIndex = i;
    break;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ah ok. I was going about it in a direct way. This makes sense, too. Just have to look for index to be a positive number, and that essentially means "contains". Thanks, guys! Also, thanks for the compatibility mention regarding the .contains().
0

String.contains() has very limited support:

Browser compatibility

Chrome              Not supported
Firefox (Gecko)     19.0 (19)
Internet Explorer   Not supported
Opera               Not supported
Safari              Not supported

You need to use a regular expression or indexOf.

if (indexItem.indexOf(substringText)!==-1) {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.