I need to replace all "*text*"
into "<strong>text</strong>"
when passing text = "normal text *words to be bolded* continue normal text"
it doesn't work because of the spaces, it works only for single-word text.
wanted result: "normal text <strong>words to be bolded</strong> continue normal text"
result: "normal text *words to be bolded* continue normal text"
I need this function to work for whatever the text is:
function bold(text){
reg = /\*(\w+)\*/g
return text.replaceAll(reg, "<strong>" + text.split(reg)[1] + "</strong>")
}
You can use the array split method.
const str = "word1 word2 pla pla"; const newStr = []; str.split(" ").forEach((val) => { newStr.push(`<strong>${val}</strong> `); }); console.log(newStr);
You should allow a set of characters to be there. Right now, you have the sequence of characters fixed.
function bold(text){
reg = /\*([\w\s]+)\*/g
return text.replaceAll(reg, "<strong>" + text.split(reg)[1] + "</strong>")
}
I assume that by 'words to be bolded', you are trying to match anything that is not asterisk.
function bold(text){ let reg = /\*([^\*]*)\*/g; return text.replaceAll(reg, "<strong>$1</strong>") }; let result = bold("normal1 *bold1 including space!* normal2 *bold2, including space?* normal3"); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.