JavaScript检查子字符串是否在字符串中的方法

作者:拾光

时间:2026-10-29

浏览:362

本文介绍在JavaScript中判断子字符串是否存在的两种常用方法。通过indexOf函数检测字符位置,若返回值不为-1则存在;利用正则表达式^和$锚点分别验证字符串开头与结尾是否包含指定内容。

文章目录

JavaScript检查子字符串是否在字符串中的方法

本文通过具体示例介绍在JavaScript中检测子字符串是否存在于字符串中的实现方式,供读者参考。


var strnew="Hello Raghu How are u"
//Checking existence in entire string
if(strnew.indexOf("Raghu") != -1 )
{
  alert("Exists");
}
/*
Checking existence at the end of string
For example, variable result1 in the following example is assigned 
the value of true because the word "Ishmael" appears at the end of 
the string. Variable result2 is assigned a value of false because 
"Raghu" doesn't appear at the end of the string.
*/
result1 = /Raghu$/.test("Call me Raghu");
result2 = /Raghu$/.test("Call me Raghu. Some years ago");
/*
Checking existence in the begining of string
In the following example, variable result1 is assigned the value 
of true because the word "Birds" appears at the beginning of the 
string. Variable result2 is assigned the value of false because 
"Birds" doesn't appear at the beginning of the string.
*/
result1 = /^Birds/.test("Birds fly");
result2 = /^Birds/.test("Big Birds fly");

感兴趣的用户可进一步查阅本站《JavaScript查找算法技巧总结》与《JavaScript数据结构与算法技巧总结》相关专题。

希望上述内容对JavaScript编程实践有所助益。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章