开发者

How to check if a string contains a specific substring

I'm working on a simple if/else jquery statement and I ran into some trouble with the variable. What I need it to do is to check if the var is true. In my case I want it to check if the has 'dont push' in it. If it's true, the html must change to 'lol'. If not, it will give a simple alert. Can anybody give me some guidance here?

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, width=device-width" />
<title>Untitled Document</title>
<link href="mobile.css" rel="stylesheet" type="text/css" media="only screen and (max-width: 480px)" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('#nietkl开发者_开发百科ikken').click(function() {
        var n = $(this).html('dont push');
        if (n == "$(this).html('dont push')"){
            $(this).html('lol')     
        } else {
            alert('lolz');
        }
    });
});
</script>
</head>

<body>
<button type="button" id="nietklikken">dont push</button>

</body>
</html>


$(this).html() will get the innerhtml value and $(this).html(arg) will set the innerhtml value. The correct usage will be below.

$('#nietklikken').click(function() {
    if ($(this).html().indexOf('dont push') > -1){
        $(this).html('lol')     
    } else {
        alert('lolz');
    }
});

You should read up more in jquery docs.

Update : It will now check if the innerhtml contains 'dont push'.


You could use the 'indexOf' operator that should tell you if a string contains another string. Try -

if ($(this).html().indexOf('dont push') != -1){
            $(this).html('lol')     
        } else {
            alert('lolz');
        }


You can get the HTML content of an element by calling the html() method with no arguments like so:

var innerHtml = $(someElement).html();

You can then check for the presence of a string by using indexOf like so:

var position = "Find the string".indexOf("the");
// position = 5

If the given string isn't present, indexOf will return -1.

var position = "Find the string".indexOf("notFound");
// position = -1

You can then use this in an if statement like so

if($(someElement).html().indexOf("dont push") >-1)
{
    // Required action here
}


In general you could use a function like this

function HasSubstring(string,substring){
    if(string.indexOf(substring)>-1)
      return true;
      return false;
}


A working javascript code to check if string contains the specific word/substring:

var inputString = "this is my sentence";
var findme = "my";

if ( inputString.indexOf(findme) > -1 ) {
  out.print( "found it" );
} else {
  out.print( "not found" );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜