Javascript: 添加动态文本到 Markdown
Javascript: Add Dynamic Text to Markdown
我有一些降价内容。例如:
let text = `This is line one,
This is para 2
![Tux, the Linux mascot](/assets/images/tux.png)
**This is title 1**
This is para 3
**This is title 2**
This is para 4`
我需要做的是在第 4 个换行符之后添加一个类似此降价之间的字符串。所以,它应该出现在 Title 1 之后,新的 markdown 应该如下所示:
`This is line one,
This is para 2
![Tux, the Linux mascot](/assets/images/tux.png)
**This is title 1**
<Ad />
This is para 3
**This is title 2**
This is para 4`
问题是我不知道如何在 javascript 中查找换行符。
如何在 javascript 中执行此操作?结果应该仍然是有效的降价。
您可以通过换行符拆分字符串。
然后循环遍历数组中的元素,然后在第n个元素之后添加文字。
let text = `This is line one,
This is para 2
![Tux, the Linux mascot](/assets/images/tux.png)
**This is title 1**
This is para 3
**This is title 2**
This is para 4`;
let split = text.split(/\n/g).filter(function(el) {
return el;
})
let newString = '';
split.forEach(function(value, key) {
if (key == 3) {
newString += value + '\n\n' + '<Ad />\n\n';
} else {
newString += value + '\n\n';
}
});
console.log(newString)
此代码段允许您在 insertAfter
索引指定的行(仅考虑非空行)之后立即插入一些 insert
字符串。没有循环。
const input = `This is line one,
This is para 2
![Tux, the Linux mascot](/assets/images/tux.png)
**This is title 1**
This is para 3
**This is title 2**
This is para 4`;
const insert = '\n\n<Ad />';
const insertAfter = 3;
const match = input.matchAll(/\S\n/g);
const position = Array.from(match)[insertAfter].index + 1;
const output = [input.slice(0, position), insert, input.slice(position)].join('');
console.log(output);
我有一些降价内容。例如:
let text = `This is line one,
This is para 2
![Tux, the Linux mascot](/assets/images/tux.png)
**This is title 1**
This is para 3
**This is title 2**
This is para 4`
我需要做的是在第 4 个换行符之后添加一个类似此降价之间的字符串。所以,它应该出现在 Title 1 之后,新的 markdown 应该如下所示:
`This is line one,
This is para 2
![Tux, the Linux mascot](/assets/images/tux.png)
**This is title 1**
<Ad />
This is para 3
**This is title 2**
This is para 4`
问题是我不知道如何在 javascript 中查找换行符。
如何在 javascript 中执行此操作?结果应该仍然是有效的降价。
您可以通过换行符拆分字符串。
然后循环遍历数组中的元素,然后在第n个元素之后添加文字。
let text = `This is line one,
This is para 2
![Tux, the Linux mascot](/assets/images/tux.png)
**This is title 1**
This is para 3
**This is title 2**
This is para 4`;
let split = text.split(/\n/g).filter(function(el) {
return el;
})
let newString = '';
split.forEach(function(value, key) {
if (key == 3) {
newString += value + '\n\n' + '<Ad />\n\n';
} else {
newString += value + '\n\n';
}
});
console.log(newString)
此代码段允许您在 insertAfter
索引指定的行(仅考虑非空行)之后立即插入一些 insert
字符串。没有循环。
const input = `This is line one,
This is para 2
![Tux, the Linux mascot](/assets/images/tux.png)
**This is title 1**
This is para 3
**This is title 2**
This is para 4`;
const insert = '\n\n<Ad />';
const insertAfter = 3;
const match = input.matchAll(/\S\n/g);
const position = Array.from(match)[insertAfter].index + 1;
const output = [input.slice(0, position), insert, input.slice(position)].join('');
console.log(output);