JavaScript: Replace '```' with '<b>' and '</b>' Alternately
Assuming that the 'text' variable contains a string with multiple occurrences of '```', you can use the 'replace()' function to replace each occurrence with '' and '' alternately. Here's an example code:
let newText = text.replace(/```/g, function(match, offset) {
return offset % 2 == 0 ? '<b>' : '</b>';
});
This code uses a regular expression to match all occurrences of '```' in the 'text' variable. The 'g' flag ensures that all occurrences are matched, not just the first one.
The 'replace()' function takes a callback function as its second argument, which is called for each match. The 'match' parameter is the matched substring, and the 'offset' parameter is the index of the match in the original string.
The callback function checks if the match index is even or odd using the modulo operator. If it's even, it returns '', otherwise it returns ''. This way, the first occurrence of '```' will be replaced with '', the second occurrence with '', the third with '', and so on.
The resulting string with the replaced HTML tags is stored in the 'newText' variable.
原文地址: https://www.cveoy.top/t/topic/mF8S 著作权归作者所有。请勿转载和采集!