xxxxxxxxxx
const string = "Hello World";
const character = "o";
const index = string.indexOf(character);
if (index !== -1) {
console.log("Character found at index:", index);
} else {
console.log("Character not found in the string.");
}
xxxxxxxxxx
var str = "Please locate where 'locate' occurs!";
var ind1 = str.indexOf("locate"); // return location of first value which founded
var ind2 = str.lastIndexOf("locate"); // return location of last value which founded
var ind3 = str.indexOf("locate", 15); // start search from location 15 and then take first value which founded
var ind4 = str.search("locate");
//The search() method cannot take a second start position argument.
//The indexOf() method cannot take powerful search values (regular expressions).
document.write("<br>" + "Length of string:", len);
document.write("<br>" + "indexOf:", ind1);
document.write("<br>" + "index of last:", ind2);
document.write("<br>" + "indexOf with start point:", ind3);
document.write("<br>" + "search:", ind4);
xxxxxxxxxx
const searchInString = (string, substring) => {
// Using the indexOf() method to search for the substring within the string
const index = string.indexOf(substring);
if (index !== -1) {
console.log(`The substring "${substring}" was found at index ${index} in the string "${string}".`);
} else {
console.log(`The substring "${substring}" was not found in the string "${string}".`);
}
};
// Example usage
const myString = "Hello, World!";
const mySubstring = "World";
searchInString(myString, mySubstring);
xxxxxxxxxx
const searchWord = (string, word) => {
const regex = new RegExp(word, 'gi');
return string.match(regex);
};
const text = "This is an example string.";
const wordToSearch = "example";
const matches = searchWord(text, wordToSearch);
console.log(matches); // Output: ["example"]
xxxxxxxxxx
const searchTerm = 'search';
const myString = 'This is a string to search within';
const position = myString.indexOf(searchTerm);
if (position !== -1) {
console.log(`The term "${searchTerm}" was found at position ${position}`);
} else {
console.log(`The term "${searchTerm}" was not found in the string`);
}