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

Time:11-14

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.

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

** Updated **

If you would like the numbers that come after =room - this does it

let value = referer.match(/=room(\d )/);

Yields

[
  '=room2',
  '2',
  index: 34,
  input: 'https://example.net:3000/page?room=room2',
  groups: undefined
]

A nicer solution is

let url = new URL(referer);
let roomNumber = url.searchParams.get('room').replace(/[^\d] /,'');
  • Related