我想在JavaScript中将所有出现的“](test”字符串替换为“ test](new / test”,而不是在markdown代码块中
示例:
replace this one ![](test/asdsa.png)
```md
don't replace this
![](test/image1.png)
```
replace this ![](test/asdsasdsds.png)
```
don't replace this
console.log("![](test/blabla.png)");
const testStr = `![](test/image3.gif)`;
```
答案 0 :(得分:0)
将字符串拆分为行数组,并使用标志通过检查行是否以反引号开头来跟踪markdown块
映射lines数组,然后使用\n
分隔符将join()转换为字符串
const textReplace = (str, subStr, newSubStr) => {
let mdBlock = false;
return str.split('\n').map(str => {
if (str.trim().startsWith('```')) {
mdBlock = !mdBlock;
}
// return unchanged string inside blocks, or run replace on string
return mdBlock ? str : str.replace(subStr, newSubStr)
}).join('\n');
};
const el = document.querySelector('textarea');
el.value = textReplace(el.value, '](test' ,'---REPLACED---' )
<textarea style="width:100%; height:250px">
replace this one ![](test/asdsa.png)
```md
don't replace this
![](test/image1.png)
```
replace this ![](test/asdsasdsds.png)
```
don't replace this
console.log("![](test/blabla.png)");
const testStr = `![](test/image3.gif)`;
```
</textarea>