简体   繁体   English

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

[英]How to replace string between two strings in javascript?

I had following string,我有以下字符串,

const str= "this is harp//foo.eps and harp//data.eps"

I need to replace the string between harp to .eps我需要将harp之间的字符串替换为.eps

My code below,我的代码如下,

const str = "this is harp//foo.eps and harp//data.eps"

const data = str.replace(/\harp.*\eps/, 'www.imge.jpg');

console.log(data);

it was returning output below,它在下面返回 output,

this is www.imge.jpg

But expected output但预计output

this is www.imge.jpg and www.imge.jpg

Try to make use non-greedy ( ? ) search and global ( /g ) modifier:尝试使用非贪婪( ? )搜索和全局( /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);

You can do it using the replace all function and the following regex您可以使用替换所有 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