簡體   English   中英

正則表達式用Javascript替換$ nth元素

[英]Regex Replace $nth element with Javascript

是否可以將$n元素替換為特定的字符串? 在我的示例中, $1元素。

例如,我想用我的字符串"other.other"替換URL "http://my.domain.com/sub/file.extension"的最后一個元素。

我的正則表達式是這樣的:/([ /([^/]+)\\.extension$

但是它也替換了“文件”之前的斜杠。

這是一個完整的示例:

var url = "http://my.domain.com/sub/file.extension";
var replace = "other.other";
var regex = new RegExp("/([^/]+)$");
console.log(url.replace(regex,replace));

我知道我可以像這樣在替換中添加斜杠: var replace = "/other.other"; 但是我想要一種不同的方法,也可以在其他項目中使用。

簡而言之,我正在尋找一種可能的方法,以替換沒有分隔符的字符。

PS:我讀到一些有關積極前瞻的信息,但我無法使其正常工作。 我知道這則帖子這篇帖子 ,但這不是我想要的。

您的代碼中進行了少量更改。請嘗試以下代碼並檢查

var url = "http://my.domain.com/sub/file.extension";
var replace = "other.other";
var regex = new RegExp("([^/]+)$");
console.log(url.replace(regex,replace));
var url = "http://my.domain.com/sub/file.extension";
url = url.split("/");
url.pop();
url.push("other.other");
url = url.join("/");
console.log(url);

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM