Home  >  Article  >  Web Front-end  >  javascript determines whether a string contains a certain string and indexOf usage examples

javascript determines whether a string contains a certain string and indexOf usage examples

高洛峰
高洛峰Original
2016-12-29 16:46:091524browse

Realize the display of advertisements by judging the specified directory

if(location.href.indexOf("http://www.jb51.net/codes/")>-1){ 
alert('ok'); 
}
var Cts = "bblText"; 
if(Cts.indexOf("Text") >= 0 ) 
{ 
alert('Cts中包含Text字符串'); 
}

indexOf usage:

Returns the character position of the first occurrence of a substring in the String object.

strObj.indexOf(subString[, startIndex])

Parameters

strObj

Required. String object or literal.

subString

Required. The substring to find in the String object.

starIndex

Optional. This integer value indicates the index within the String object at which to begin the search. If omitted, the search is from the beginning of the string.

Description

The indexOf method returns an integer value indicating the starting position of the substring within the String object. If the substring is not found, -1 is returned.

If startindex is a negative number, startindex is treated as zero. If it is greater than the largest character position index, it is treated as the largest possible index.

Perform the search from left to right. Otherwise, the method is the same as lastIndexOf.

Example

The following example illustrates the use of the indexOf method.

function IndexDemo(str2){ 
var str1 = "BABEBIBOBUBABEBIBOBU" 
var s = str1.indexOf(str2); 
return(s); 
}

Ignore case for indexOf in JavaScript

The indexOf function method in JavaScript returns an integer value indicating the starting position of the substring within the String object. If the substring is not found, -1 is returned. If startindex is negative, startindex is treated as zero. If it is greater than the largest character position index, it is treated as the largest possible index.
The indexOf function performs searches from left to right. Otherwise, the method is the same as lastIndexOf.

The following example illustrates the usage of the indexOf function method

function IndexDemo(str2){ 
var str1 = "BABEBIBOBUBABEBIBOBU" 
var s = str1.indexOf(str2); 
return(s); 
}

For more javascript articles on determining whether a string contains a certain string and indexOf usage examples, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn