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
Asked
Active
Viewed 2.1k times
-1
-
3Can you show us your attempt? your code? what issue you faced – Prasad Telkikar Sep 17 '19 at 04:59
-
I tried using str1.includes(str2) for the same string i mentioned earlier and alerted it returned false. – Raghavendra M.S Sep 17 '19 at 05:05
5 Answers
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
-
If these are the strings var str1 = "hidUnfiledAmt_000"; var str2 = "spanId_UnfiledAmt_Amt" then it fails – Raghavendra M.S Sep 17 '19 at 10:37
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

Mohit Arora
- 11
- 3
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