Search code examples
javascriptregexstring-matching

How to extract exact value from this string with match and regex?


Hi,

I have this string:

var referer = "https://example.net:3000/page?room=room2"

I want to get only what comes after =room no matter its position so I tried this:

var value = referer.match(/[?&;](.+?)=([^&;]+)/g);

but Im getting this ["?room=room2"] whereas the expected output is just 2. Please see this fiddle: https://jsfiddle.net/8fduhLep/

What am I missing here?

Thank you.


Solution

  • You can use substring and indexOf:

    var referer = "https://example.net:3000/page?room=room2"
    
    const res = referer.substring(referer.indexOf('=room') + 5) //add 5 to account for length of string
    console.log(res)

    If it's not the only parameter, you can parse the URL and get the value of the room parameter, then use the method above:

    var referer = "example.net:3000/page?room=room2&someotherquery=something"
    
    
    var roomVal = new URL("https://example.net:3000/page?room=room2").searchParams.get('room')
    const res = roomVal.substring(roomVal.indexOf('=room') + 5)
    console.log(res)

    With regex:

    var referer = "example.net:3000/page?room=room2&someotherquery=something"
    
    const regex = /room=room(\w+)/g
    const res = regex.exec(referer)[1]
    
    console.log(res)