Is there an equivalent function in JavaScript or jQuery similar to strpos
in PHP?
I want to locate a string inside an element on a page. The string I'm looking for is:
td class="SeparateColumn"
I would like something where I can run it like this to find:
if $("anystring") then do it
strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.
The strpos() function finds the position of the first occurrence of a string inside another string. Note: The strpos() function is case-sensitive.
How to find if a word or a substring is present in the given string. In this case, we will use the includes() method which determines whether a string contains the specified word or a substring. If the word or substring is present in the given string, the includes() method returns true; otherwise, it returns false.
I assume you mean check whether a string contains a character, and the position in the string - you'd like to use the indexOf()
method of a string in JS. Here are the relevant docs.
Okay, so you'd like to search the whole page! The :contains()
selector will do that. See the jQuery docs for :contains
.
To search every element in the page, use
var has_string = $('*:contains("search text")');
If you get jQuery elements back, then the search was a success. For example, on this very page
var has_string=$('*:contains("Alex JL")').length //has_string is 18 var has_string=$('*:contains("horsey rodeo")').length //has_string if 0. So, you could an `if` on this and it would work as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With