Regex with JavaScript - Taking only part of String

1

Let's say I have the following string:

str = "http://www.google.com/joao.pedro?a=b";

So I want to get just john.pedro using JavaScript .

I think you can do with Regex somehow, can anyone help me how?

I thought of something like, use this regular expression:

(http://www.google.com/)([\d\w\.]+)

And get the value that would be between the second parentheses. In PHP you can do something like this using the preg_match function, but what about JavaScript?

    
asked by anonymous 01.03.2018 / 04:28

5 answers

1

In this case, for solution you need to use the match function.

This function will return an array with occurrences of the regular expression.

In this application:

string = "http://www.google.com/joao.pedro?a=b";
a = string.match(/(http:\/\/www\.google\.com\/)([\d\w\.]+)/);

returns an array:

Array [ "http://www.google.com/joao.pedro", "http://www.google.com/", "joao.pedro" ]

See that the first occurrence is the entire body of the string, and the subsequent occurrences would be the occurrences that the regular expression found in the string.

    
01.03.2018 / 04:59
1

Very simple and does not need regex:

var str = "http://www.google.com/joao.pedro?a=b/";
var valor= str.substring(str.lastIndexOf(".com/")+5,str.lastIndexOf("?"));

Result: joao.pedro

explanation ".com/" or only "/" , the bar may appear at the end of the link and the codo would have to have validations to avoid or treat the string +5 is to remove the .com / from the result

    
07.03.2018 / 12:34
0

A. With RegExp

One of the infinite (ie: .* x Infinity ) possibilities, a generic one is:

str.match(/^.*(:\/\/)*.*\/(.*)[#\?].*/)[2]

which can be translated from the beginning ( ^ ), any string 0- "Infinity" ( .* ), except for and followed by (://) (aka protocol), character string followed of / (domain), string (path - what we want), string started by ? (querystring) or # (hash location).

B. No RegExp

  • Partitioning String - "one line" version:

    (((str
      .split('://')[1] || '')
      .split('/')[1] || '')
      .split('?')[0] || '')
      .split('#')[0]
    
  • Using HTMLHyperlinkElementUtils :

    var a = document.createElement('a')
    a.href="http://www.google.com/joao.pedro?a=b"
    a.pathname.substring(1)
    
  • * I'm not taking into account other little used URI parts on the Web, such as username and password.

        
    09.03.2018 / 16:55
    0
    const regex = /[a-z]\/([\w.]+)/g;
    
    const rege = (text) => {
    let user = regex.exec(text);
     return hue[1];
    }
    
    console.log(
      rege("http://www.google.com/joao.pedro?a=b")
    )
    
        
    23.03.2018 / 15:57
    0

    My regex looks like this:

       /(\w+\.\w+)(?=\?)/
    
  • (\w+\.\w+) Search for text that has . followed by text.
  • (?=\?) use positive lookahead, that is, looking forward search for ?
  • Running on regex101

        
    23.03.2018 / 16:23