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?

4

3 回答 3

5

您需要设置值,而不仅仅是调用方法:

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

要使其不区分大小写,请使用此正则表达式:

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

虽然如果您在“?”上拆分字符串可能会更容易,然后用“&”拆分键/值对,然后用“=”拆分它们。

于 2013-04-20T19:59:58.670 回答
2

有人可以帮助我并告诉我我做错了什么吗?

replace不会改变字符串,但会返回一个新字符串——你必须将它分配到某个地方。

另外,我如何使它不区分大小写?

i标志传递给RegExp构造函数

link = link.replace(new RegExp('&pos'+position+'=[^&]*', 'i'), '');
于 2013-04-20T20:01:27.027 回答
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

于 2013-04-20T20:05:50.397 回答