0
let str = 'text text example.com/?isExample=true more text'

if (str.match(/.com/i)) {
 ...
}

How can I get the whole example.com link based on just that one condition? I need only the link, not the text as well.

So the expected result would be example.com/?isExample=true

vcosiekx
  • 65
  • 2
  • 9
  • https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-string <-- basic idea – epascarello Feb 12 '20 at 17:20
  • 2
    Or use an existing library e.g. linkify-js or twitter-text (from https://stackoverflow.com/a/41603438 ) – Rup Feb 12 '20 at 17:21

4 Answers4

2

Here's one solution: Use a positive lookahead assertion, (?=…[your condition here]…) followed by the whole pattern you want to match.

let str = 'text text example.com/?isExample=true more text'
console.log(str.match(/(?=\S*\.com)\S+/i));

This will match any sequence of one or more non-whitespace characters (\S+) so long as that sequence contains a subsequence that matches your condition. The \S* inside the assertion means that the matched subsequence may begin anywhere within the sequence, not just at the beginning.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • what about `.co.in` `.uk` etc? – AZ_ Feb 12 '20 at 17:28
  • @AZ_ I don't think that's within the scope of the question. Obviously, this pattern won't match every possible domain name. Although if those specific domains were part of your requirement, you could of course use `/(?=\S*(\.com|\.co\.in|\.uk))\S+/i` – p.s.w.g Feb 12 '20 at 17:30
  • I agree with that. but then why not simple `/\S*\.com\S*/`? why a lookahead? – AZ_ Feb 12 '20 at 17:37
  • @AZ_ I agree, that's a simpler solution, and it's probably what I'd go with in my own code for this _specific_ case. However, I initially read the question as a more general problem -- given patterns, `x` and `y`, how do you match instances of `x` only if they also satisfy `y`, in which case, you'd use `(?=zy)x` where `z` is some prefix of `x`. Even if OP's self-answer suggests he/she was able to solve the problem without advanced regex, this answer may still be helpful for future readers as it introduces lookaheads as a concept for overlaying two patterns on top of each other. – p.s.w.g Feb 12 '20 at 17:49
0

Figured out it works best for me this way:

let str = 'asdsadf example.com/?isExample=true adpdor'

str.split(/\s/).forEach(word => {

    if (word.match(/.com/i)) console.log(word)

})
vcosiekx
  • 65
  • 2
  • 9
0

You can use \S+\.com.\S+

let re = new RegExp(/\S+\.com.\S+/),
str = "text text example.com/?isExample=true more text",
result = str.match(re);

console.log(result);
zfrisch
  • 8,474
  • 1
  • 22
  • 34
0

You can use following regex

let str = 'text text example.co.in/?isExample=true&y=3 more text'
let res = str.match(/\w+(\.[a-z]{2,3})+\/?\??(\w+=\w+&?)*/)[0];
console.log(res)
AZ_
  • 3,094
  • 1
  • 9
  • 19