简体   繁体   中英

How to find a text using javascript or jquery.

I need to find a text from a paragraph using java script. Is there any code in JavaScript like we do in c# to find a text using "string.Contains("")" method.

Pls help...

Thanks Guys..

You can use str.search()

It will return the position of match and -1 if not found

http://www.w3schools.com/jsref/jsref_search.asp

equivalent of string.Contains("") is indexOf (returns -1 if subString doesnt exist in a string).

you can do :

var myString = "foo";
var myParagraphText = $('#myParagraphId').text();

if(myParagraphText.indexOf(myString) != -1){
    //myParagraphText contains myString
} 

您可以使用string.indexOf(“ text”)方法,该方法将返回“字符串”中“文本”的索引,如果在字符串中找不到文本,则返回-1。

var n = $('p').text();
var regex = new RegExp('text to search for', "i");
if(regex.exec(n) != null) {
  // text found
} else {
  //text not found
}

Use the search() function

If it returns -1, the string is not present Non-negative number means, string is present

var str="hello there";
alert(str.search("there"));

For searching text inside a block element .

var str="your block"
str.search("text to find");


str.indexOf("text to find"); 

return the index of the text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM