How to check whether a string contains a substring in JavaScript? In JavaScript, you have numerous options for determining whether a string contains a substring. Here are a few of the most prevalent approaches: String. prototype.includes() : The includes() method determines whether a string contains a given substring and returns a boolean value (true or false). const str = 'Hello, world!'; const substring = 'world'; if (str.includes(substring)) { console.log('Substring found.'); } else { console.log('Substring not found.'); } String. prototype.indexOf() : The indexOf() method returns the first index in the string at which a substring can be found. If the substring cannot be retrieved, the function returns -1. const str = 'Hello, world!'; const substring = 'world'; if (str.indexOf(substring) !== -1) { console.log('Substring found at index ' + str.indexOf(substring)); } else { console.log('Substring not found.'); }
How do I redirect to another webpage in Javascript? You can set window.location.href to redirect to another webpage. Set the location property to the URL of the page to which you want to visit. Here's how to go about it: // Redirect to another webpage window.location.href = "https://www.example.com"; Replace "https://www.example.com" with the URL of the page to which you want to redirect. This line of code instructs the browser to load the provided URL, forwarding the user to that page. If you wish to imitate a link click to initiate a redirect, use the following method: // Simulate a click on a link to redirect var link = document.createElement('a'); link.href = "https://www.example.com"; link.click(); This code generates an invisible link element, assigns the target URL to its href attribute, and then fires a click event on it. The user will be redirected to the selected webpage as well. Practice More on: https://interviewplus.ai/developer