/    Sign up×
Bounties /Pin to ProfileBookmark

How do you check if a string contains a substring in JavaScript?

+ 1,000
Copy linkTweet thisAlerts:
Dec 05.2022
to post a answer
JavaScript

1 Replies

Copy linkTweet thisAlerts:
@JaySODec 05.2022 — You can use the includes() method. This method returns a boolean value indicating whether the string contains the substring. Here's an example:


const str = 'The quick brown fox jumps over the lazy dog';

if (str.includes('fox')) {
console.log('The string contains the substring "fox"');
}


Alternatively, you can use the indexOf() method to check for the presence of a substring in a string. This method returns the index at which the substring is found, or -1 if the substring is not found. Here's an example:


const str = 'The quick brown fox jumps over the lazy dog';

if (str.indexOf('fox') !== -1) {
console.log('The string contains the substring "fox"');
}


Both methods work similarly, but includes() is easier to read and more concise. It's a newer method, so it might not be supported in older browsers. If you need to support older browsers, you can use indexOf() instead.
×

Success!

Help @hq spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @junehugh,
tipped: article
amount: 500 SATS,

tipper: @buildinteractive,
tipped: article
amount: 1000 SATS,

tipper: @farhadmalegam,
tipped: article
amount: 1000 SATS,
)...