繁体   English   中英

如何在 javascript 中的两个字符串之间替换字符串?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM