将第一个出现的值替换为一个值,将第二个出现的值替换为另一个值

时间:2020-05-23 03:57:08

标签: javascript

提供此原始字符串...

Test text _with bold_ and perhaps one another text _with bold in the same string_.

...如何有效地将第一次出现的“ _”替换为“ ”,并将第二次出现的“ _”替换为“ ”,以实现以下结果:

Test text <b>with bold</b> and perhaps one more text <b>with bold in the same string</b>.

注意:我有数百个这些字符串的数组,需要进行此过程才能在页面中呈现。

2 个答案:

答案 0 :(得分:1)

您可以为此使用正则表达式。

替换模式如下:

await Location.getCurrentPositionAsync({});的末尾带有标志_(.*?)_-因此它将替换,直到满足所有情况为止。

正则表达式中的g说,在开头?(非贪婪)之后的第一个_中,它将停止匹配。

_说,用此替换匹配的字符串。 <b>$1</b>是指括号$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;

答案 1 :(得分:0)

您可以运行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("_");
}

while循环之后,您可以将任意元素的innerHTML分配给变量test。