-1

I want to check if my string contain particular substring.

1.What function should i use to perform this in javascript or jquery or using regex

for example

var a = "i am string";
var b = "i am webpage";

if(var_a_has_string)
{
 alert("it is string")
}

if(var_b_has_webpage)
{
alert("it is webpage")
}

sorry for repetition being a beginner i found some similar question but did not get the given answers here

https://stackoverflow.com/questions/5038105/checking-if-a-string-contains-a-certain-substring

Fastest way to check a string contain another substring in Javascript?

2.which function to be used if i want to retrieve the particular substring from my string

like "webpage" string or "string" string

for example

var a = "i am string";
var b = "i am webpage";

if(var_a_has_string)
{
 var c = get_string_from_a(a)
}

if(var_b_has_webpage)
{
 var d = get_webpage_from_b(b)
}
Community
  • 1
  • 1
Hitesh
  • 4,098
  • 11
  • 44
  • 82

4 Answers4

1

Just like the other answers.. string.indexOf is what you're looking for. It tells you the location of the substring within the string you're checking. -1 for not found.

var stringToCheck = "i am stringpage";

var a = "i am string";
var b = "i am webpage";

if(stringToCheck.indexOf(a) > -1){
     alert("it is string")
}

if(stringToCheck.indexOf(b) > -1){
   alert("it is webpage")
}

JSFIDDLE

bluetoft
  • 5,373
  • 2
  • 23
  • 26
0

You can use the javascript function "indexOf"

It returns an integer, and -1 if the string hasn't been found.

 if (yourString.indexOf("stringToCheck") >= 0){
     //Insert some logic here
 }
Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66
0

As mentioned, indexOf is what you need.

The MDN documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

0

To check if string contains another substring using Javascript use the below code

var str = "Hello world, welcome to Javascript Coding.";
var n = str.indexOf("welcome");

//Returns 13

var s = "foo";
console.log(s.indexOf("oo") > -1)

//returns true

The other way to do the same thing is using includes

var str = "Hello World, Welcome to Javascript Coding";
console.log(str.includes("Welcome to"));    // true
console.log(str.includes("Javascript")); // true
console.log(str.includes("To be", 1)); // false  
Coder
  • 61
  • 6