Javascript get 字符串介于两个字符串之间



我喜欢获取两个字符串之间的值。 这就是我用作占位符来更改两者之间的内容。 所以基本上我把这些自定义 [[num}] 附加到每个标签上。我试图制作它的数据库。然后我正在尝试根据某些参数对其进行自定义/预定义编辑。所以基本上,如果有办法获取/更改/删除打开和关闭字符串中的内容。

<script>
var num = 14;
</script>

.HTML

[[14}]<img width="50" height="50" src="//cdn.com/img5.jpg" alt="comment-image">[{14]] [[15}]<img width="50" height="50" src="//cdn.com/img6.jpg" alt="comment-image">[{15]]

这是一个按标签号提取子字符串的 JavaScript 函数:

function extractField(str, num) {
    var startLabel = '[['+num+'}]';
    return str.substring(str.indexOf(startLabel)+startLabel.length, str.indexOf('[{'+num+']]'));
}

它的工作原理是查找起始标签的索引,添加标签字符串的长度,然后提取所有内容直至结束标签。

用法示例:

str='[[14}]<img width="50" height="50" src="//cdn.com/img5.jpg" alt="comment-image">[{14]] [[15}]<img width="50" height="50" src="//cdn.com/img6.jpg" alt="comment-image">[{15]]';
extractField(str, 14);
"<img width="50" height="50" src="//cdn.com/img5.jpg" alt="comment-image">"

最新更新