提供此原始字符串...
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>.
注意:我有数百个这些字符串的数组,需要进行此过程才能在页面中呈现。
答案 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。