2017-05-30 4 views

Antwort

1

Sie dieses

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>"; 
     } 

    } 
+1

Aber das wird nicht schließenden Tags erstellen. – Luca

4

Sie können diese regexp verwenden /\*([^\*]+)\*/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);

verwenden können

Als Funktion

const str = `Hi *John* We wish you* Happy Birthday * and blah blah blah..`; 
 
function bold(str) { 
 
\t const regex = /\*([^\*]+)\*/g; 
 
\t const subst = `<b>$1</b>`; 
 
\t // The substituted value will be contained in the returned variable 
 
\t return str.replace(regex, subst); 
 
} 
 
const result = bold(str); 
 
console.log('Substitution result: ', result);

+0

mit dieser Regexp, wie Anfang und Ende Tag ersetzen –

+0

Es funktioniert gut, Ist es möglich, Winkelfilter für diese –

+0

erstellen Sie benötigen dies eine Funktion zu sein? –

2

Ich denke, das Ihr Problem lösen.

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 { 
 
    \t replace = "<b>"; 
 
    } 
 
    
 
    if(str.search(/\*/) !== -1) { 
 
    \t replaceInStr(str, replace); 
 
    } else { 
 
    \t console.log(str); 
 
    } 
 
}

+0

Es funktioniert gut, Ist es möglich, Winkelfilter dafür zu erstellen –

0

Try this:

var txt = "Hi *John* We wish you* Happy Birthday * and blah blah blah.."; 
 

 
txt = txt.replace(/\*(.*?)\*/g, "<b>$1</b>"); 
 
console.log(txt);

Verwandte Themen