-1

How to check if one string contains in another string in js or jquery For example : String str1 = asbf_000.String str2 = asbf; Then str1.contains(str2) should return true.I tried using includes() in JS but did not work

Raghavendra M.S
  • 1
  • 1
  • 1
  • 2

5 Answers5

2

"contains" is not a function is javascript, but "includes" is. You can use it like

let str1 = "asbf_000";
let str2 = "asbf";
const isSubstring = str1.includes(str2);
console.log(isSubstring); // this will log true in the console

You can check a working demo here on jsfiddle

thenaamsake
  • 264
  • 3
  • 12
2

You can check it using indexOf() function by checking str1.indexOf(str2)

var str1 = 'asbf_000'
var str2 = 'asbf';
console.log(checkExistOrnot(str1,str2))

function checkExistOrnot(str1,str2)
{
 if (str1.indexOf(str2) >= 0)
  return true
 else
   return false
}
Nijin P J
  • 1,302
  • 1
  • 9
  • 15
1

The simplest way to check substring is by using method "indexOf".

<script>
    function subString(str1,str2){
       return str1.indexOf(str2)
    }
    var result = subString("asbf_000","asbf");
</script>

if result is greater then -1 then substring exist else not

1
let a = 'Hello world';
let b = 'ld';

let position = a.indexOf(b);

this will give you the position of first occurrence of string b in string a and if it is not present in string a, it would give you -1

Summy
  • 443
  • 3
  • 5
  • 14
0

You can use String#indexOf().

Based on the docs, .indexOf() for Strings accepts a search value parameter. If the search value is found, it returns a non-negative value. If it does not find your search value, it returns -1.

let word = 'Hello world!';
let query = 'world';
let anotherQuery = 'value';

word.indexOf(query); // returns 6 - which is a non-negative value
word.indexOf(anotherQuery); // returns -1

Which you can use it this way.

let isExist = word.indexOf(query) !== -1;

Or you can write a function for it

function find(haystack, needle) {
  let isFound = haystack.indexOf(needle);

  return isFound !== -1;
}

let isExist = find(word, query);
Rin Minase
  • 308
  • 2
  • 5
  • 19