[英]How to replace string between two strings in javascript?
我有以下字符串,
const str= "this is harp//foo.eps and harp//data.eps"
我需要將harp
之間的字符串替換為.eps
我的代碼如下,
const str = "this is harp//foo.eps and harp//data.eps"
const data = str.replace(/\harp.*\eps/, 'www.imge.jpg');
console.log(data);
它在下面返回 output,
this is www.imge.jpg
但預計output
this is www.imge.jpg and www.imge.jpg
嘗試使用非貪婪( ?
)搜索和全局( /g
)修飾符:
const str = "this is a harp//foo.eps and a harp//data.eps and harp//data.eps" const data = str.replace(/harp(.*?)eps/g, 'www.imge.jpg'); console.log(data);
您可以使用替換所有 function 和以下正則表達式來做到這一點
const str = "this is harp//foo-two.eps and harp//data-9.eps" const newSTr = str.replaceAll(/harp\/\/[A-Za-z\-0-9]+\.eps/g, 'www.imge.jpg') console.log(newSTr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.