Как найти подстроку jquery

How would our group find out if a particular string contains a certain substring? Only with the help of jquery, please.

mythicalcoder's user avatar

asked May 18, 2010 at 4:13

4

You don’t really need jQuery for such a simple thing, you can simply use the indexOf method of String objects, e.g.:

var str = "foobar";
var containsFoo = str.indexOf('foo') >= 0; // true

The indexOf method returns the character index where the first occurrence of the specified value is encountered, if not found, it returns -1.

answered May 18, 2010 at 4:16

Christian C. Salvadó's user avatar

2

Why use 10 characters when 100 will do?

Here’s the requested jQuery plugin:

jQuery.isSubstring = function(haystack, needle) {
    return haystack.indexOf(needle) !== -1;
};

Usage:

$.isSubstring("hello world", "world")); // true;​​​​​​​​​​​

answered May 18, 2010 at 6:52

Anurag's user avatar

AnuragAnurag

140k36 gold badges220 silver badges257 bronze badges

2

If your limited to jQuery which is just JavaScript… you can use the filter

var subgtSel = $("#jquerySelector").filter(function(i) {
    // do your filter here
    return $(this).attr("data-timestamp") <= subMsg.CreateDateTimeStamp;
});

the subgtSel becomes your new jQuery now with the relevant filter in the above. In the above, I am looking for all div elements that have an attribute that is less than the subMsg.CreateTimeStamp.

If your looking for a particular substring… you can do the following with jQuery right in the selector

var sel = $("#jquerySelector:contains('text')");

see http://api.jquery.com/contains-selector/

answered May 18, 2010 at 5:18

Jason Jong's user avatar

Jason JongJason Jong

4,3102 gold badges25 silver badges33 bronze badges

Say a web page has a string such as «I am a simple string» that I want to find. How would I go about this using JQuery?

Reinstate Monica Please's user avatar

asked May 29, 2009 at 15:23

Keith Donegan's user avatar

Keith DoneganKeith Donegan

26.2k34 gold badges94 silver badges129 bronze badges

jQuery has the contains method. Here’s a snippet for you:

<script type="text/javascript">
$(function() {
    var foundin = $('*:contains("I am a simple string")');
});
</script>

The selector above selects any element that contains the target string. The foundin will be a jQuery object that contains any matched element. See the API information at: https://api.jquery.com/contains-selector/

One thing to note with the ‘*’ wildcard is that you’ll get all elements, including your html an body elements, which you probably don’t want. That’s why most of the examples at jQuery and other places use $(‘div:contains(«I am a simple string»)’)

user202729's user avatar

user202729

3,2803 gold badges23 silver badges36 bronze badges

answered May 29, 2009 at 15:34

Tony Miller's user avatar

6

Normally jQuery selectors do not search within the «text nodes» in the DOM. However if you use the .contents() function, text nodes will be included, then you can use the nodeType property to filter only the text nodes, and the nodeValue property to search the text string.

    $('*', 'body')
        .andSelf()
        .contents()
        .filter(function(){
            return this.nodeType === 3;
        })
        .filter(function(){
            // Only match when contains 'simple string' anywhere in the text
            return this.nodeValue.indexOf('simple string') != -1;
        })
        .each(function(){
            // Do something with this.nodeValue
        });

answered May 29, 2009 at 16:20

BarelyFitz's user avatar

BarelyFitzBarelyFitz

1,96713 silver badges17 bronze badges

3

This will select just the leaf elements that contain «I am a simple string».

$('*:contains("I am a simple string")').each(function(){
     if($(this).children().length < 1) 
          $(this).css("border","solid 2px red") });

Paste the following into the address bar to test it.

javascript: $('*:contains("I am a simple string")').each(function(){ if($(this).children().length < 1) $(this).css("border","solid 2px red") }); return false;

If you want to grab just «I am a simple string». First wrap the text in an element like so.

$('*:contains("I am a simple string")').each(function(){
     if($(this).children().length < 1) 
          $(this).html( 
               $(this).text().replace(
                    /"I am a simple string"/
                    ,'<span containsStringImLookingFor="true">"I am a simple string"</span>' 
               )  
           ) 
});

and then do this.

$('*[containsStringImLookingFor]').css("border","solid 2px red");

BlitZ's user avatar

BlitZ

12k3 gold badges49 silver badges67 bronze badges

answered May 29, 2009 at 16:40

Slim's user avatar

SlimSlim

5,5857 gold badges31 silver badges30 bronze badges

4

If you just want the node closest to the text you’re searching for, you could use this:

$('*:contains("my text"):last');

This will even work if your HTML looks like this:

<p> blah blah <strong>my <em>text</em></strong></p>

Using the above selector will find the <strong> tag, since that’s the last tag which contains that entire string.

answered May 29, 2009 at 16:49

nickf's user avatar

nickfnickf

535k198 gold badges648 silver badges721 bronze badges

4

Take a look at highlight (jQuery plugin).

answered May 29, 2009 at 15:25

Chris Doggett's user avatar

Chris DoggettChris Doggett

19.7k4 gold badges61 silver badges86 bronze badges

0

Just adding to Tony Miller’s answer as this got me 90% towards what I was looking for but still didn’t work. Adding .length > 0; to the end of his code got my script working.

 $(function() {
    var foundin = $('*:contains("I am a simple string")').length > 0;
 });

answered Dec 10, 2014 at 9:27

Pixelomo's user avatar

PixelomoPixelomo

6,3034 gold badges45 silver badges57 bronze badges

2

this function should work. basically does a recursive lookup till we get a distinct list of leaf nodes.

function distinctNodes(search, element) {
    var d, e, ef;
    e = [];
    ef = [];

    if (element) {
        d = $(":contains(""+ search + ""):not(script)", element);
    }
    else {
            d = $(":contains(""+ search + ""):not(script)");
    }

    if (d.length == 1) {
            e.push(d[0]);
    }
    else {
        d.each(function () {
            var i, r = distinctNodes(search, this);
            if (r.length === 0) {
                e.push(this);
            }
            else {
                for (i = 0; i < r.length; ++i) {
                    e.push(r[i]);
                }
            }
        });
    }
    $.each(e, function () {
        for (var i = 0; i < ef.length; ++i) {
            if (this === ef[i]) return;
        }
        ef.push(this);
    });
    return ef;
}

answered Jun 13, 2013 at 18:42

danatcofo's user avatar

danatcofodanatcofo

6938 silver badges18 bronze badges

I remember those day when I am a fresher to programming. To complete my assignments related to string operations I always take help from Google. Sometime to find out a Syntax or Sometime for Examples. In my view string operations are little bit confusing to freshers. During programming there are several possibilities to do with a string. Some of them are String Concatenation, Finding the position of a Character in a String, Split or retrieve few part of the String. In this session for beginner of Jquery to make their journey easier I am explaining all the Jquery String Functions in details. The programming language I used here is Jquery. But keep remember theoretically fundamentals of String Operations are same for all languages. In implementation only Syntax’s are differ.

charAt(n)

In a String array to know the Character of a specific index we use charAt() function. Let’s take an example you have a string “THIS IS A TABLE.”. In this String if I want to know the Character of index 3 charAt() function can did that. Look the example below.

var myStr = "THIS IS A TABLE.";
var ch = myStr.charAt(3);

Output will be : S

charAt() function accepts integer value as the param & returns String Character. charAt(n) calculates index starting from 0.

charCodeAt(n)

charCodeAt() works similarly like chatAt() function. The only difference is while charAt() returns Character of a specific index charCodeAt() returns Unicode of the Character. Look at the example below.

var myStr = "THIS IS A TABLE.";
var ch = myStr.charCodeAt(1);

Output will be : 72

72 is the Unicode for Capital H. charCodeAt() accepts integer as the param & returns Unicode value.

concat(string1, string2, .., stringN)

String Concatenation is a very common used String operation. Let’s take a case where in two variables you are getting name of a person. First Name & Last Name. In this case to display the whole name we required to do string Concatenation operation. Look at the example below.

var strFirstName = "Biswabhusan ";
var strLastName = "Panda";
var wlcmMsg = "You are welcome!";
var ch = strFirstName.concat(strLastName, " ", wlcmMsg);

Output will be : Biswabhusan Panda You are welcome!

Using Jquery concat() method (Originally derived from JavaScript ) you can concatenate n number of strings. This method accepts n number of strings as parameters. To apply this method choose the first string variable & then concatenate others.

fromCharCode(n1, n2, …, nX)

Refer to the method name fromCharCode() it Converts Unicode value to Character. This is a static method of String object. To use this method you can use String.fromCharCode(). Look at the example below.

var ch = String.fromCharCode(67);

Output will be : C

This function accepts n number of Unicode values.

indexOf(searchvalue, [start])

indexOf() method returns the position of a specific value in a string. It return -1 if the value not found in string. While checking the value in string this method considers uppercase & lowercase characters. Using this method we can know whether a specific word exist in the string or not. Look at the example below.

var myStr="Hello, You are welcome to the my blog.";
var ch=myStr.indexOf("welcome");

Output will be : 14

indexOf() accepts 2 parameters. First parameter is the keyword you want to search in the string. Second parameter is from which index you want to search rest of the string. By default this is 0. 0 means you are searching the string from the beginning.

lastIndexOf(searchvalue, [start])

lastIndexOf() method work in similar fashion of indexOf() method. The only difference is it shows the searched value position at the last occurrence of the string. For an example if in a String “welcome” appears two times lastIndexOf() method returns the 2nd occurrence of welcome. If searched value not exist in the string it returns -1. This is case sensitive. Welcome is not equal to welcome. While returning the index it counts from the beginning of the string.

var myStr="This is Biswabhusan Panda, You can only Call Biswabhusan.";
var ch=myStr.lastIndexOf("Biswabhusan");

Output will be : 44

lastIndexOf() accepts 2 parameters like indexOf() method. First parameter is the keyword you want to search in the string. Second parameter is from which index you want to search rest of the string. By default this is 0. 0 means you are searching the string from the beginning.

substr(start, [length])

substr() string function used to retrieve part of a string. This function accepts 2 parameters start & length in integer value. Start says from which index you want the part of the string. Length is the number of characters you want from the start index. Let’s take an example. I have a string “My Car is blue.”. In this string if I am applying substr(2, 3) it will return Car.

var myStr="My Car is blue.";
var ch=myStr.substr(2, 3);

Output will be : Car

substring(from, [to])

substring() works similarly like substr(). But while substr() accepts Start & Length as the parameters substring() accepts From & To. From is the index from which you want your part of the string. To is the index upto which you want to retrieve in part of the string. Let’s take the same example as shown in substr. You can see the difference while substr(2, 3) return “Car” substring(2, 3) will return “C”.

var myStr="My Car is blue.";
var ch=myStr.substring(2, 3);

Output will be : C

toLowerCase()

toLowerCase() converts uppercase letters to lowercase. If in a string you have mix of upper & lower case letter this function will return that string in lowercase only.

var myStr="Biswabhusan";
var ch = myStr.toLowerCase();

Output will be : biswabhusan

toUpperCase()

toUpperCase() converts lowercase letters to uppercase. If in a string you have mix of upper & lower case letter this function will return that string in uppercase only.

var myStr="Biswabhusan";
var ch = myStr.toUpperCase();

Output will be : BISWABHUSAN

match(regexp)

match() function accepts regular expression & returns the matches as an Array Object. Look at the example below.

var myStr="The rain in SPAIN stays mainly in the plain";
var ch=myStr.match(/ain/g);

Output will be : ain, ain, ain

replace(searchvalue, newvalue)

replace() function is one more very useful function of string operation. In-case in a string if you want to replace some characters with another characters this function helps. It accepts 2 parameters. First parameter is the search value & second parameter is the replacement for search value. Look at the example below.

var myStr="This is an awesome Blog.";
var ch = myStr.replace("awesome ","interesting ");

Output will be : This is an interesting Blog.

search(searchvalue)

search() method help to search a specific value in a string. If search value exists in the string it returns the index or else if string doesn’t contain the value it returns -1.

var myStr = "Welcome to my Blog!";
var ch = myStr.search("my");

Output will be : 11

slice(start, [end])

slice() method extract part of the string in a new string. It accepts 2 parameters start & end. Depending upon start & end value it returns the new string.

var myStr = "Visit Jquery Blog!";
var n = myStr.slice(6, 12);

Output will be : Jquery

split(separator, [limit])

split() method used to divide a string from a specific character. It returns sub-strings in array. Split method accepts 2 parameters. Separator & limit. In separator if you use empty char “” it will divide all characters individually as a sub-string. Limit is always an integer value which specifies the number of splits.

var myStr = "How are you doing today?";
var arr = myStr.split(" ",3);

Output will be : How,are,you

contains selector

Description: Select all elements that contain the specified text.

  • version added: 1.1.4jQuery( «:contains(text)» )

    text: A string of text to look for. It’s case sensitive.

The matching text can appear directly within the selected element, in any of that element’s descendants, or a combination thereof. As with attribute value selectors, text inside the parentheses of :contains() can be written as a bare word or surrounded by quotation marks. The text must have matching case to be selected.

Example:

Finds all divs containing «John» and underlines them.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<title>contains demo</title>

<script src="https://code.jquery.com/jquery-3.7.0.js"></script>

<div>Malcom John Sinclair</div>

$( "div:contains('John')" ).css( "text-decoration", "underline" );

Demo:

The jQuery :contains() Selector is used to check whether a string contains a substring in jQuery.

Set the substring you are searching for in the contains() method as shown below:

$(document).ready(function(){
   $("p:contains(Video)").css("background-color", "blue");
});

Now, let us see the complete code to check whether a string contains a substring or not:

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
      $(document).ready(function(){
         $("p:contains(Video)").css("background-color", "blue");
      });
   </script>
</head>
<body>

<h1>Tutorialspoint</h1>

<p>This is demo text.</p>
<p>Free Tutorials</p>
<p>Free Video Tutorials</p>

</body>
</html>

Понравилась статья? Поделить с друзьями:
  • Как найти архивное объявление на авто ру
  • Не пропеклись оладьи внутри как исправить
  • Как найти тендеры на рекламу
  • Как найти площадь прямоугольника 3 класс ответы
  • Как найти нужного тебе мужчину