[英]Replacing closing HTML tags with HTML tag + \n
I'm trying to replace generally closing html tags with the closing tag + a line break, i found similar posts here on SO, none really helped me to accomplish what I'm looking for. 我试图用结束标记+换行符代替通常结束的html标记,所以我在这里找到了类似的帖子,没有一个真正帮助我完成想要的事情。
</li>
would be </li>\\n
</li>
应该是</li>\\n
<img some property />
would be <img some property />\\n
<img some property />
将是<img some property />\\n
I managed to do that in php with the following funtion, which works well: 我设法通过以下功能在php中做到了,效果很好:
public static function addLBinHTML($htmlcode){
$pattern= array('~(</.*?>)~','(/>)');
$replace= array('${1} Hallo \n ','/>\n ');
return preg_replace($pattern, $replace, $htmlcode);
}
I'm trying to do the same in JavaScript / jQuery and I'm failing on getting the variable(in php regex ${1}
). 我试图在JavaScript / jQuery中执行相同的操作,但未能获取变量(在php regex
${1}
)。
I tried with .split .join and with .replace, and I think .replace is the right way to go. 我尝试了.split .join和.replace,我认为.replace是正确的方法。
Here is what I got (my last and hopefully closest attempt) 这就是我得到的(我最后一次也是最接近的尝试)
function setLinebreaks(taID){
var strContent = $('#'+taID).val();
var regex = new RegExp("</.*?>", "gi");
strContent.replace(regex, "${1} \n ")
.replace(/\/>/g,'/> \n ');
console.log(strContent);
$('#'+taID).val(strContent);
}
Thanks in advance for your help 在此先感谢您的帮助
You have to capture the regular expression with brackets, assign the replaced string and replace ${1}
by $1
: 你必须捕捉与括号中的正则表达式, 指定替换字符串和替换
${1}
的$1
:
var regex = new RegExp("(</.*?>)", "gi");
strContent = strContent.replace(regex, "$1 \n ")
.replace(/\/>/g,'/> \n ');
Or you can simply put the replace
methods into the val
function. 或者,您可以简单地将
replace
方法放入val
函数中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.