How to use a variable in indexOf() method?

I linked the problem I am working on below, and I linked my proposed solution so far. What I am trying to do is use the indexOf() method to check a string variable against the string. However, the indexOf() method wants string literals. Is it possible to literalize the string variable? If not, how do I pass the string literal the variable contains into the method?

function mutation(arr) {
let x = arr[0]
let y = arr[1]

let comp1 = x.split("")
let comp2 = y.split("")

x = comp1.sort()
y = comp2.sort()
x = x.join(" ")
y = y.join(" ")

if(x.length > y.length){
if(y.length > x.length){}


mutation(["hello", "hey"]);

This is finding the index of the string “${y}” in x. If you want to use the string in the variable y, then just use y:


The variable y is storing a string. You don’t need to do anything special to use it as a string.

1 Like

const paragraph = ‘The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?’;

const searchTerm = ‘dog’;
const indexOfFirst = paragraph.indexOf(searchTerm);

console.log(The index of the first "${searchTerm}" from the beginning is ${indexOfFirst});
// expected output: “The index of the first “dog” from the beginning is 40”

console.log(The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))});
// expected output: “The index of the 2nd “dog” is 52”