Jason Axelrod
Jason Axelrod

Reputation: 7805

Having issues with a replace function in Javascript

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?

Upvotes: 1

Views: 89

Answers (3)

Ian
Ian

Reputation: 50933

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 "=".

Upvotes: 5

Xotic750
Xotic750

Reputation: 23502

<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

Upvotes: 0

Bergi
Bergi

Reputation: 665455

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'), '');

Upvotes: 2

Related Questions