0

Match substring

function testRegExp(s, sub_s) { var a; for(var i =0;i<=s.length;i++) { a=s.match(sub_s); return a.join(";"); }} Plz help me identify the error

1st Aug 2020, 1:23 PM
Priyankita Srivastava
Priyankita Srivastava - avatar
6 Answers
+ 1
.join method works on arrays only , You could remove that for loop as it doesn't do anything if I am not wrong and rewrite the function as follow function testRegExp(s, sub_s) { var a; a=s.match(sub_s); return a; } But still it will be helpful if you could provide a description with what output you expect for a certain input
1st Aug 2020, 2:18 PM
Abhay
Abhay - avatar
0
const testRegExp = (s, sub_s) => s.split(" ").filter(word => word.includes(sub_s)).join(";");
1st Aug 2020, 5:55 PM
Gordon
Gordon - avatar
0
thanks for considering my code Sample Input 1: Anbutdsirbutdbutbutareviewbutobutverman but Sample Output 1: but;but;but;but;but;but the program should output all occurrences of "sub_s" separated by semi colons.
2nd Aug 2020, 3:57 AM
Priyankita Srivastava
Priyankita Srivastava - avatar
0
You need to remove the for/loop as stated by Abhay. To get the output you want, you need to pass a RegExp object to the match method instead of a string. This will allow you to use the g flag to indicate that you want to search the whole string and return all matches found. You can do this manually or use the RegExp constructor. Using your example the RegExp object will look this /but/g, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp https://code.sololearn.com/Wx4YTYUMRf6o/#js
2nd Aug 2020, 6:29 AM
ODLNT
ODLNT - avatar
0
thanks for ur help. The output for code is coming out correct but still there is "FAILED TEST #17" BEING DISPLAYED SO i am not able to submit.
4th Aug 2020, 2:16 PM
Priyankita Srivastava
Priyankita Srivastava - avatar
0
The output for code is coming out correct but still there is "FAILED TEST #17" BEING DISPLAYED SO i am not able to submit. SORRY for troubling you again...
5th Aug 2020, 4:37 AM
Priyankita Srivastava
Priyankita Srivastava - avatar