xxxxxxxxxx
var string = "Hello world!";
var n = string.search("w"); //now n equals 6
xxxxxxxxxx
'a nice string'.indexOf('nice') !== -1 //true
'a nice string'.indexOf('nice', 3) !== -1 //false
'a nice string'.indexOf('nice', 2) !== -1 //true
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 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`);
}