Hi *John* We wish you* Happy Birthday * and blah blah blah..
我可以在每对*之间获取文本并返回
Hi <b>john</b> We wish you <b> Happy Birthday </b> and blah blah blah..
答案 0 :(得分:4)
您可以使用此正则表达式/\*([^\*]+)\*/g
const regex = /\*([^\*]+)\*/g;
const str = `Hi *John* We wish you* Happy Birthday * and blah blah blah..`;
const subst = `<b>$1</b>`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
作为一项功能
const str = `Hi *John* We wish you* Happy Birthday * and blah blah blah..`;
function bold(str) {
const regex = /\*([^\*]+)\*/g;
const subst = `<b>$1</b>`;
// The substituted value will be contained in the returned variable
return str.replace(regex, subst);
}
const result = bold(str);
console.log('Substitution result: ', result);
答案 1 :(得分:2)
我认为这可以解决您的问题。
str = "Hi *John* We wish you* Happy Birthday * and blah blah blah..";
replaceInStr(str, "<b>");
function replaceInStr(str, replace) {
str = str.replace(/\*/, replace);
if(replace === "<b>") {
replace = "</b>";
} else {
replace = "<b>";
}
if(str.search(/\*/) !== -1) {
replaceInStr(str, replace);
} else {
console.log(str);
}
}
&#13;
答案 2 :(得分:1)
你可以像这样使用
var stringArray = str.split("*");
var stringOut = "";
for (var i = 0 ; i < stringArray.length; i++) {
stringOut += stringArray[i];
if (i % 2 !== 0) {
stringOut += "</br>";
}
else
{
stringOut += "<br>";
}
}
答案 3 :(得分:0)
试试这个:
var txt = "Hi *John* We wish you* Happy Birthday * and blah blah blah..";
txt = txt.replace(/\*(.*?)\*/g, "<b>$1</b>");
console.log(txt);
&#13;