-1

How to search for "completed" in string "test1|completed"

Is there any reular expression which I can used to slove this problem. I used spilt function

user3180402
  • 579
  • 2
  • 7
  • 16

4 Answers4

1
if ('test1|completed'.indexOf('completed') !== -1) console.log('found')

indexOf will return -1 when the string is not found. It's faster and easier than regex, but if you want:

if ('test1|completed'.match(/completed/)) console.log('found')

See also: How to check whether a string contains a substring in JavaScript?

Community
  • 1
  • 1
bjb568
  • 11,089
  • 11
  • 50
  • 71
0

You don't need RegEx here. Simply use String.prototype.indexOf function, like this

"test1|completed".indexOf("completed") !== -1

The indexOf function will return the starting index of the string being searched in the original string. If not found, it returns -1. So, if the result of indexOf is not equal to -1, then the string being searched is there in the original string.

Note: In the next version of JavaScript (ECMAScript 6), there will be a function called contains in the String objects and you can use them like this

var str = "To be, or not to be, that is the question.";

console.log(str.contains("To be"));       // true
console.log(str.contains("question"));    // true
console.log(str.contains("nonexistent")); // false
console.log(str.contains("To be", 1));    // false
console.log(str.contains("TO BE"));       // false
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0
/completed/

will serve your purpose

var str = "test1|completed";
var res = /completed/.test(str);
console.log(res);
aelor
  • 10,892
  • 3
  • 32
  • 48
0

you can alert this and see that it will return the matched string If not matched it will return null.

alert("test1|completed".match("completed"));
Prabhat Jain
  • 346
  • 1
  • 8