Javascript 替换所有不在 markdown 代码块内的字符串
Javascript replace all string not inside a markdown code block
我想在 javascript 中用 "test](new/test" 替换所有出现的 "](test" 字符串,但不在降价代码块中
示例:
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)`;
```
将字符串拆分为行数组,并使用标志通过检查行是否以反引号开头来跟踪降价块
映射行数组,然后用 \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>
我想在 javascript 中用 "test](new/test" 替换所有出现的 "](test" 字符串,但不在降价代码块中
示例:
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)`;
```
将字符串拆分为行数组,并使用标志通过检查行是否以反引号开头来跟踪降价块
映射行数组,然后用 \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>