1

Okay, so I have some variables in javascript...

var link = 'http://8wayrun.com/streams/multi?type=3&pos1=1.teamsp00ky.video&pos2=1.teamsp00ky.chat&pos3=1.nycfurby.chat';
var position = 2;

As you can see, I have a link and a position. Using the position var I would like to replace some text in the link field. I would like to strip &pos2=1.teamsp00ky.chat from the link. Naturally, I have to do some basic regular expressions; the problem comes into when I try to use the position var in the regex. I just can't figure it out.

In PHP I could do the following:

preg_replace('/&pos'.$position.'=[^&]*/i', '', $link);

I tried the following in JS, but its not working:

link.replace(new RegExp('&pos'+position+'=[^&]*'), '');

Could someone help me out and tell me what I'm doing wrong? Also, how would I make it case-insensitive?

1
  • In fact, in PHP preg_replace doesn't modify $link either. You still have to do the assignment. Commented Apr 20, 2013 at 20:18

3 Answers 3

5

You need to set the value, not just call the method:

link = link.replace(new RegExp('&pos'+position+'=[^&]*'), '');

To make it case insensitive, use this regex:

new RegExp('&pos'+position+'=[^&]*', "i")

Although it might make it easier if you split the string on the "?", then split up the key/value pairs by "&", and then split them by "=".

Sign up to request clarification or add additional context in comments.

1 Comment

@JasonAxelrod Haha no problem, it's just different in Javascript.
2

Could someone help me out and tell me what I'm doing wrong?

replace does not mutate the string, but returns a new one - you'd have to assign it somewhere.

Also, how would I make it case-insensitive?

Pass the i flag to the RegExp constructor.

link = link.replace(new RegExp('&pos'+position+'=[^&]*', 'i'), '');

Comments

0
<div id="result"></div>

var link = 'http://8wayrun.com/streams/multi?type=3&pos1=1.teamsp00ky.video&pos2=1.teamsp00ky.chat&pos3=1.nycfurby.chat';
var position = 2;

var start = link.indexOf("pos2");

var end = link.indexOf("&", start);

document.getElementById("result").textContent = link.slice(0, start) + link.slice(end + 1);

on jsfiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.