How to check if string contains string

How to check if string contains string

Fastest way to check a string contain another substring in JavaScript?

I’m working with a performance issue on JavaScript. So I just want to ask: what is the fastest way to check whether a string contains another substring (I just need the boolean value)? Could you please suggest your idea and sample snippet code?

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

9 Answers 9

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You have three possibilites:

It cannot be said with certainty which method is faster. The differences between the browsers is enormous. While in Chrome 10 indexOf seems to be faster, in Safari 5, indexOf is clearly slower than any other method.

You have to see and try for your self. It depends on your needs. For example a case-insensitive search is way faster with regular expressions.

Update 2018:

Just to save people from running the tests themselves, here are the current results for most common browsers, the percentages indicate performance increase over the next fastest result (which varies between browsers):

Chrome: indexOf (

98% faster)
Firefox: cached RegExp (

18% faster)
IE11: cached RegExp(

10% faster)
Edge: indexOf (

18% faster)
Safari: cached RegExp(

Note that cached RegExp is: var r = new RegExp(‘simple’); var c = r.test(str); as opposed to: /simple/.test(str)

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

The Fastest

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

Does this work for you?

Edit: This may not be faster than a RegExp if the string2 contains repeated patterns. On some browsers, indexOf may be much slower than RegExp. See comments.

Edit 2: RegExp may be faster than indexOf when the strings are very long and/or contain repeated patterns. See comments and @Felix’s answer.

In ES6, the includes() method is used to determine whether one string may be found within another string, returning true or false as appropriate.

Here is jsperf between

As the result shown in jsperf, it seems both of them perform well.

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

ETA: indexOf and charAt both perform similarly terrible on Chrome Mobile according to Browser Scope data listed on jsperf.com

Wish you a nice day, sir!

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

2022 string research benchmark

From Felix Kling’s answer, and with tests I’ve done with given links.

Most used browser :

Chrome and NE are both based on Chromium => same performances.

ci = case insensitive
/ = same as left

Tests results

string lengthFirefoxSafariChromium
shortcached RegExp cicached RegExp ciindexOf & / ciworth
RegExp & / ciRegExp ciRegExp & / ciworse
longcached RegExpcached RE & / ci & reg ciindexOfworth
indexOf ciindexOf ciRegExpworse

Operations/sec comparison

browserFirefoxSafariChromium
cached RegExp1.3M425k1.2M
diff1.08x >
cached RegExp case sensitive28M31M42M
diff1.44/1.35x >
indexOf27M25M1.9B
diff70/76x >
indexOf case sensitive13.8M18.5M1.9B
diff137/103x >

Firefox best method : cached regexp case insensitive
Chrome best method : indexOf / indexOf case insensitive
Safari best method : cached RegExp case insensitive

Chrome has widely better performances than the two others.

Regexes are really good for complex and/or pattern research/replacement, but not for a global research, and that in all languages, because of what it is.

How to check if a String contains another String in a case insensitive manner in Java?

Say I have two strings,

I am pretty sure that contains() is case sensitive, however I can’t determine this for sure from reading the documentation. If it is then I suppose my best method would be something like:

All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity?

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

19 Answers 19

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:

EDIT: If s2 contains regex special characters (of which there are many) it’s important to quote it first. I’ve corrected my answer since it is the first one people will see, but vote up Matt Quail’s since he pointed this out.

You want to call Pattern.quote() on s2:

The Apache Commons library is very useful for this sort of thing. And this particular one may be better than regular expressions as regex is always expensive in terms of performance.

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

A Faster Implementation: Utilizing String.regionMatches()

Using regexp can be relatively slow. It (being slow) doesn’t matter if you just want to check in one case. But if you have an array or a collection of thousands or hundreds of thousands of strings, things can get pretty slow.

The presented solution below doesn’t use regular expressions nor toLowerCase() (which is also slow because it creates another strings and just throws them away after the check).

The solution builds on the String.regionMatches() method which seems to be unknown. It checks if 2 String regions match, but what’s important is that it also has an overload with a handy ignoreCase parameter.

Speed Analysis

This speed analysis does not mean to be rocket science, just a rough picture of how fast the different methods are.

I compare 5 methods.

Results (by calling the method 10 million times):

Results in a table:

Analysis Test Code

If you’re interested how the analysis was performed, here is the complete runnable application:

How to check if one string contains in another string in js or jquery [duplicate]

How to check if one string contains in another string in js or jquery For example : String str1 = asbf_000.String str2 = asbf; Then str1.contains(str2) should return true.I tried using includes() in JS but did not work

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

5 Answers 5

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

«contains» is not a function is javascript, but «includes» is. You can use it like

You can check a working demo here on jsfiddle

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

The simplest way to check substring is by using method «indexOf».

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

You can check it using indexOf() function by checking str1.indexOf(str2)

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

Which you can use it this way.

Or you can write a function for it

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

Not the answer you’re looking for? Browse other questions tagged javascript jquery or ask your own question.

Linked

Related

Hot Network Questions

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Check if a string contains a substring in JavaScript

One of the most common tasks in any programming language is to find out whether a string contains a given substring. JavaScript provides multiple ways to check if a string contains a substring.

In this tutorial, we will look into six different ways to check if a substring is a part of a string or not. Let’s start with the most common one: indexOf() method.

1. String indexOf() Method

The indexOf() method is case-sensitive and accepts two parameters. The first parameter is the substring to search for, and the second optional parameter is the index to start the search from (default index is 0).

2. String includes() Method

The includes() method was introduced in ES6 and works in all modern browsers except Internet Explorer. Unlike the good old indexOf() method, which returns the starting index of the substring, the includes() method returns true if the string contains the specified substring. Otherwise, it returns false.

Similar to indexOf() method, includes() is also case-sensitive and accepts an optional second parameter, an integer which indicates the position where to start searching for.

3. String search() Method

4. String match() Method

Another way to check if a string contains a substring is to use the match() method. It accepts a regular expression as a parameter and searches the string for a match. If it finds the matches, it returns an object, and null if no match is found.

If the regular expression does not include the g modifier, the match() method will return only the first match in the string.

5. RegExp.test() Method

The regular expression test() method checks if a match exists in a string. This method returns true if it finds a match, otherwise, it returns false.

We first need to create a regular expression for the substring and then test it against the target string.

For more details on how to create and use regular expressions, check out Introduction to JavaScript Regular Expressions.

6. Lodash Library

Lodash is a third-party library that provides _.includes() method to check the presence of a substring in a string. This method returns true if a match is found, otherwise false.

Summary

If you have any questions or feedback, please feel free to send me a tweet anytime.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

How to check if a string contains a WORD in javascript? [duplicate]

I’m interested in finding if a string contains a word.

For example, if I apply a search for «on» for the string, «phones are good», it should return false. And, it should return true for «keep it on the table».

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

8 Answers 8

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You first need to convert it into array using split() and then use includes()

Just need to pass whitespace » » to split() to get all words

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

You can split and then try to find:

In addition, some method is very efficient as it will return true if any predicate is true.

You can use of 101regex website when you need to work around them (it helps). Words with custom separators aswell.

Explaination :

I am creating here multiple capturing groups for each possibily :

(^.*\son$) on is the last word

(^on\s.*) on is the first word

(^on$) on is the only word

(^.*\son\s.*$) on is an in-between word

\s means a space or a new line

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

A simple version could just be splitting on the whitespace and looking through the resulting array for the word:

This just splits by whitespace though, when you need parse text (depending on your input) you’ll encounter more word delimiters than whitespace. In that case you could use a regex to account for these characters. Something like:

How to check if string contains string. Смотреть фото How to check if string contains string. Смотреть картинку How to check if string contains string. Картинка про How to check if string contains string. Фото How to check if string contains string

I would go with the following assumptions:

Therefore, I would write my code as follows:

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *