[英]Replace first occurrence with one value and second with another
Giving this original string...给这个原始字符串...
Test text _with bold_ and perhaps one another text _with bold in the same string_.
... how to efficiently replace the first occurrence of " _ " with "< b >" and the second occurrence " _ " with "< /b >" to achieve the following result: ...如何有效地将第一次出现的“_”替换为“<b>”,将第二次出现的“_”替换为“</b>”以达到以下结果:
Test text <b>with bold</b> and perhaps one more text <b>with bold in the same string</b>.
Note: I have an array of hundreds of those strings that will need to go through this process in order to render in the page.注意:我有一个包含数百个字符串的数组,这些字符串需要通过此过程 go 才能在页面中呈现。
You can use regex for this.您可以为此使用正则表达式。
The replace-pattern is the following:替换模式如下:
_(.*?)_
with the flag g
at the end - so it will replace until all occurances are satisfied. _(.*?)_
最后带有标志g
- 因此它将替换直到满足所有出现。
The ?
?
in the regex says it will stop matching at the first _
afert the opening _
(non-greedy).在正则表达式中表示它将在第一个_
之后的开头停止匹配_
(非贪婪)。
<b>$1</b>
says replace the matched string with this. <b>$1</b>
表示用这个替换匹配的字符串。 Where the $1
refers to the content matched in the brackets ()
其中$1
指的是括号()
中匹配的内容
var text = "This is _bold text_ and here _some more_"; var text_replaced = text.replace(/_(.*?)_/g, '<b>$1</b>'); document.getElementById('result').innerHTML = text_replaced;
<span id="result" />
You can run a while loop which checks if there any more underscores in the text and replaces them, assuming that there must be an even number of "_" in the text:您可以运行一个 while 循环来检查文本中是否还有下划线并替换它们,假设文本中必须有偶数个“_”:
var test = "text _with bold_ and perhaps one another text _with bold in the same string_.";
b_index = test.indexOf("_");
while (b_index != -1) {
test = test.replace("_", "<b>");
test = test.replace("_", "</b>");
b_index = test.indexOf("_");
}
After the while loop, you can assign the innerHTML of whichever element you wish to the variable test.在 while 循环之后,您可以将所需的任何元素的 innerHTML 分配给变量 test。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.