我需要一些帮助才能有效地完成某些逻辑。我需要删除此字符串末尾的所有break标记和换行符,然后在完成所有字符串操作后将它们添加回字符串。
str = "<br><br>My test string is here and <br> has some text in it.<br><br><br>\n\n<br>\n<br>";
// Code here that pops off all the break tags.
new_str = "<br><br>My test string is here and <br> has some text in it.";
// Break tags stored in a variable maybe?
end_tags = '<br><br><br>\n\n<br>\n<br>';
// More manipulation of the string.
final_str = "<br><br>My test string is here and <br> has..." + end_tags;
我知道这可以在正则表达式中优雅地完成,我只是碰壁,使其工作得足够快。
答案 0 :(得分:0)
您可以简单地使用正则表达式来解决您的问题:
// Match all <br> and \n tags in the end
const matches = str.match(/^(.+?)((?:\<br\>|\n)+)$/)
// Matches = [Entire String, Stuff before the ending, all the end <br>s]
const [_, new_str, end_tags] = matches
// Match all <br> and \n tags in the end
var matches = str.match(/^(.+?)((?:\<br\>|\n)+)$/)
// Matches = [Entire String, Stuff before the ending, all the end <br>s]
var new_str = matches[1], end_tags = matches[2]
答案 1 :(得分:0)
使用正则表达式在replace
上调用str
方法,以便在最后进行匹配:
str = "<br><br>My test string is here and <br> has some text in it.<br>\n\n<br><br>";
new_str = str.replace(/(?:<br>|[\n\r])*$/, function(match) {
end_tags = match;
return '';
});
console.log(end_tags);
&#13;
答案 2 :(得分:0)
编辑:这是我实现这个
的方式var str = "<br><br>My test string is here and <br> has some text in it.<br><br><br>\n\n<br>\n<br>";
// replace line breaks with <span> to make things easier
var replaceStr = str.replace(/(\r\n|\r|\n)/g, '<span>');
// this get's the last line breaks or new lines at the end of the
// string but also one extra string at the begining
// i.e it gets .<br><br><br>\n\n<br>\n<br> notice the (.) in front
var pattern = /(([^<br])(<br>|<span>)<br>.+|<span>.+|$).+$/gm;
var found = replaceStr.replace(pattern, function(match) {
var firstChar = match.charAt(0);
var remainder = match.substring(1);
// add hello to remainder string
return firstChar + ' add text, do stuff here ' + remainder;
});
// replace all spans to new line back
var finalResult = found.replace(/(<span>)/g, '\n');