<div>This is demo</div>
console.log("js preparation");
/o/.test('Hello World!');
'Hello World!'.indexOf('o') > -1;
!!'Hello World!'.match(/o/);
'Hello World!'.includes('o')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
RegExp#test | |
String#indexOf | |
String#match | |
String#includes |
Test name | Executions per second |
---|---|
RegExp#test | 8190612.0 Ops/sec |
String#indexOf | 16165686.0 Ops/sec |
String#match | 7249782.5 Ops/sec |
String#includes | 14298517.0 Ops/sec |
I'll provide an in-depth explanation of the benchmark test cases, options compared, pros and cons, and other considerations.
Benchmark Test Cases
The provided JSON contains four individual test cases:
RegExp#test
: Tests the test()
method of regular expressions.String#indexOf
: Tests the indexOf()
method of strings.String#match
: Tests the match()
method of strings with a regular expression pattern.String#includes
: Tests the includes()
method of strings.Options Compared
The options compared in these test cases are:
RegExp#test
:/o/.test('Hello World!');
'Hello World!'.match(/o/)
or 'Hello World!'.includes('o')
String#indexOf
:indexOf('o') > -1;
String#match
:!!'Hello World!'.match(/o/);
(note the doublebang !!
)'Hello World!'.includes('o')
Pros and Cons
Here are some pros and cons of each option:
RegExp#test
:String#indexOf
:includes()
or a similar function that achieves the same result.String#match
:Other Considerations
includes()
and match()
) requires support for modern JavaScript features like template literals, arrow functions, or let
/const
declarations. This means that older browsers may not support these features.RegExp#test
) might require specific browser versions or configurations to work correctly.Alternatives
If you need to support older browsers or want alternative approaches for these string comparison methods, consider the following:
indexOf()
method with a negative index check (-1
).includes()
method (available in most modern JavaScript engines since ECMAScript 2015).test()
method with regular expression patterns.In summary, the new syntax (includes()
and match()
) is more concise, readable, and efficient. However, it requires support for modern JavaScript features and may not work in older browsers.