Home > Net >  Can I use find method to iterate through the characters of a string?
Can I use find method to iterate through the characters of a string?

Time:10-27

Can I use find() method to search through a string not an array?

like this:

const text = "welcome";
const output = text.find(letter => letter === "e");

CodePudding user response:

Use String#split to convert the string to an array of characters first:

const text = "welcome"; 
const output = text.split('').find(letter => letter === "e");
console.log(output);

CodePudding user response:

You can use the .find method to iterate the characters of a string but first you must transform the string to an array of characters, for example:

Array.from('string').find(char => char === 't')

CodePudding user response:

Strings don't have a find() method.

As suggested in the other answer, you can use split() to create an array of characters. But in the case where you're using find() with a callback function that just tests element equality, you can use the indexOf() method, which exists for both arrays and strings.

const text = "welcome";
const output = text.indexOf("e");
console.log(output);

CodePudding user response:

Yes, it is possible to use Array#find() directly on a string. The array methods like .find() are intentionally made generic to be usable with any array-like object.

To use an array method on something else, use Function#call():

const text = "welcome"; 

const output = Array.prototype.find.call(text, letter => letter === "e");

console.log(output);

Alternatively, using Function#apply():

const text = "welcome"; 

const output = Array.prototype.find.apply(text, [letter => letter === "e"]);

console.log(output);

See also What is the difference between call and apply?

CodePudding user response:

Many ways to convert to an array before being able to use .find() (or other array methods).

Here is another using the spread syntax:

const text = "welcome"; 
const output = [...text].find(letter => letter === "e");
console.log(output);

CodePudding user response:

const string = 'hello';

const found = string.split('').find(element => element == 'h');

console.log(found);

is this what you mean?

find() is originally for finding an array element so you need to convert the string to array and then split it using split() and now you can use the find() to find the string element

  • Related