0

I have the following items in my array:

var mystring;
var myname = "Level 1-1";
var myarray = [
    "My Level 1-11 Ticket",
    "My Level 1-1 Ticket",
    "My Level 10-1 Ticket",
    "My Level 10-11 Ticket"
];

 for (var i = 0; i <= myarray.Count - 1; i++) {
     if (myname == ) {
         mystring = myarray[i];
         break;
     }
 }

Now, I want to find out if there is an item in the array that contains the string "Level 1-1". But I only want to return the string that exactly contains "Level 1-1", I don't want to return similar strings like "Level 1-11".

The strings in myarray will only have values like: Level 1-1, Level 1-2, Level 1-10, Level 1-11, Level 10-1, Level 10-11.

The strings in myarray will never have values like: Level 1, Level 1-, Level -1, Level -1-1.

How can I only return the item of myarray that exactly contains "Level 1-1"?

hygull
  • 8,464
  • 2
  • 43
  • 52

2 Answers2

1

You can use regex for this,

let arr = ["My Level 1-11 Ticket",
"My Level 1-1 Ticket",
"My Level 10-1 Ticket",
"My Level 10-11 Ticket"];

let inputStr = "Level 1-1";

let result = arr.find(e => e.match(RegExp(`\\b${inputStr}\\b`)));

console.log(result);

Or if your string can appear start or end or middle, you can use this one

    let arr = ["My Level 1-11 Ticket",
        "My Level 1-1 Ticket",
        "My Level 10-1 Ticket",
        "My Level 10-11 Ticket",
        "Level 11-11 Ticket",
        "My Level 12-11"];

        let inputStr = "Level 11-11";

        let result = arr.find(e => e.match(RegExp(`([^\\w]|^)${inputStr}([^\\w]|$)`)));

        console.log(result);
Vivek Bani
  • 3,703
  • 1
  • 9
  • 18
0

The use of regular expressions will be more useful in this case.

In Regular expression, ^ is used to match start, $ is to match end & \s is to match whitespace (newline, tab, space etc.).

function getTheExactStrings(myarray, myname) {
    // Write a regular expression as per your need to match the substrings
    const regex = new RegExp(`.*(\\s+|^)${myname}(\\s+|$).*`);

    // Iterate over array items and try to return true/false using `test() method`
    return myarray.filter((name) => {
        return regex.test(name);
    });
}

// start
var mystring;
var myname = "Level 1-1";
var myarray = [
    "My Level 1-11 Ticket",
    "My Level 1-1 Ticket",
    "My Level 10-1 Ticket",
    "My Level 10-11 Ticket",
];

// Call the function to get result
console.log(getTheExactStrings(myarray, myname)); // [ 'My Level 1-1 Ticket' ]
  

I think, this should solve your problem. You can make changes in the above code to fulfil your need. I would suggest you to write a function that can test it with different different arrays.

References

In case if you want to know about Javascript's regular expressions, have aa look into below documentations.

hygull
  • 8,464
  • 2
  • 43
  • 52