This question already has answers here:
How to keep Quill from inserting blank paragraphs (`<p><br></p>`) before headings with a 10px top margin?
(3 answers)
Closed 1 year ago.
I have some HTML as a string
var str= "<p><br/></p>"
How do I strip the p tags from this string using JS.
here is what I have tried so far:
str.replace(/<p[^>]*>(?:\s| )*<\/p>/, "") // o/p: <p><br></p>'
str.replace("/<p[^>]*><\\/p[^>]*>/", "")// o/p: <p><br></p>'
str.replace(/<p><br><\/p>/g, "")// o/p: <p><br></p>'
all of them return me same str as above, expected o/p is:
str should be ""
what im doing wrong here?
Thanks
You probably should not be using RegExp to parse HTML - it's not particularly useful with (X)HTML-style markup as there are way too many edge cases.
Instead, parse the HTML as you would an element in the DOM, then compare the trim()med innerText value of each <p> with a blank string, and remove those that are equal:
var str = "<p><br/></p><p>This paragraph has text</p>"
var ele = document.createElement('body');
ele.innerHTML = str;
[...ele.querySelectorAll('p')].forEach(para => {
if (para.innerText.trim() === "") ele.removeChild(para);
});
console.log(ele.innerHTML);
You should be able to use the following expression: <p[^>]*>( |\s+|<br\s*\/?>)*<\/p>
The expression above looks at expressions enclosed in <p>...</p> and matches them against , whitespace (\s+) and <br> (and / variations).
I think you were mostly there with /<p[^>]*>(?:\s| )*<\/p>/, but you just needed to remove ?: (not sure what you were trying to do here), and adding an additional case for <br>.
const str = `
<p><br></p>
<p><br/></p>
<p><br /></p>
<p> <br/> </p>
<p> </p>
<p> </p>
<p><br/> </p>
<p>
<br>
</p><!-- multiline -->
<p><br/> don't replace me</p>
<p>don't replace me</p>
`;
const exp = /<p[^>]*>( |\s+|<br\s*\/?>)*<\/p>/g;
console.log(str.replace(exp, ''));
Related
How can I replace my binding data's < br > with line break?
like: passing data:
Hello< br >welcome to this group< br >type your text
and viewing data will be :
Hello
welcome to this group
type your text
to replace < br > with line break, I have used [innerHTML] like, <p [innerHTML]="a.Details">; but here problem is, all letter are come as Capital formate.
Is there any alter form?
You can use different div.
eg.
<div> Hello </div>
<div> welcome to this group </div>
<div> type your text </div>
You could split the text from <br> and will have an array of each line.
on the HTML side you can loop through the lines and use <p *ngFor=let line of text>{{line}}</P> to display them.
.ts file
text: string = 'Hello< br >welcome to this group< br >type your text';
lines: string[] = this.text.split('< br >');
.html file
<p *ngFor="let line of lines">{{line}}</p>
You can use this way to update your code :
<p [innerHTML]="replaceBreaksWithLineBreaks(a.Details.toLowerCase())"></p>
and your JS function
replaceBreaksWithLineBreaks(text: string): string {
return text.replace(/<br>/g, '\n');
}
I currently load a value from my database straight into a hidden textarea.
<textarea name="text" id="text" style="visibility:hidden">
[textarea]Content showing raw [b]HTML[/b] or any other code
Including line breaks </a>[/textarea]
</textarea>
From there I pick up the textarea's content and run it trough several replace arguments with a simple Javascript, like
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function parser() {
post_text=post_text.replace(/\r?\n/g, "<br>");
post_text=post_text.replace(/\[size=1\]/g, "<span style=\"font-size:80%\">");
post_text=post_text.replace(/\[url=(.+?)\](.+?)\[\/url\]/g, "$2 <img src=\"images/link.gif\" style=\"border:0px\">");
post_text=post_text.replace(/\[url\](.+?)\[\/url\]/g, "$1 <img src=\"images/link.gif\" style=\"border:0px\">");
document.getElementById('vorschau').innerHTML = post_text;
}, false);
</script>
<div id="vorschau"></div>
to render it into HTML which is then parsed by the Browser, so I do all the formatting of the entries on the Frontend/client side.
However, the textarea may also contain such an UBB tag:
[textarea]Content showing raw [b]HTML[/b] or any other code
Including line breaks </a>[/textarea]
I currently just replace the textarea UBB elements like any other content
post_text=post_text.replace(/\[textarea\]/g, "<textarea id=\"codeblock\" style=\"width:100%;min-height:200px;\">");
post_text=post_text.replace(/\[\/textarea\]/g, "</textarea>");
The issue with this is that my other code
post_text=post_text.replace(/\r?\n/g, "<br>");
post_text=post_text.replace(/\</g, "<");
post_text=post_text.replace(/\>/g, ">");
Does not skip the content within the [textarea][/textarea] elements resulting in a textarea filled with this:
Content showing raw <b>HTML</b> or any other code<br>Including line breaks </a>
Above example
So how do I prevent to replace anything within [textarea][/textarea] (which can occur more than once in id="text")?
What you might do, is use a dynamic pattern that captures from [textarea] till [/textarea] in group 1, and use an alternation to match what you want to replace.
Then use a callback function for replace. Check if group 1 exists, and if it does return it unmodified. If it does not, we have a match outside of the text area.
An example of the pattern with the alternation and match for <
(\[textarea][^]*\[\/textarea])|<
(\[textarea][^]*\[\/textarea]) Capture group 1, match from [textarea] till [/textarea]
| Or
< Match literally
Regex demo
Note to double escape the backslash in the RegExp constructor.
(Assuming this is the right order of replacements:)
const replacer = (text, find, replace) => text.replace(
new RegExp(`(\\[textarea][^]*\\[\\/textarea])|${find}`, "g"),
(m, g1) => g1 ? g1 : replace
);
document.addEventListener('DOMContentLoaded', function parser() {
let post_text = document.getElementById('text').value;
post_text = post_text.replace(/\[size=1]/g, "<span style=\"font-size:80%\">");
post_text = post_text.replace(/\[url=(.+?)](.+?)\[\/url\]/g, "$2 <img src=\"images/link.gif\" style=\"border:0px\">");
post_text = post_text.replace(/\[url](.+?)\[\/url]/g, "$1 <img src=\"images/link.gif\" style=\"border:0px\">");
post_text = replacer(post_text, "\\r?\\n", "<br>");
post_text = replacer(post_text, "<", "<");
post_text = replacer(post_text, ">", ">");
post_text = post_text.replace(/\[textarea]/g, "<textarea id=\"codeblock\" style=\"width:100%;min-height:200px;\">");
post_text = post_text.replace(/\[\/textarea]/g, "</textarea>");
document.getElementById('vorschau').innerHTML = post_text;
}, false);
<textarea name="text" id="text" rows="10" cols="60">
[textarea]Content showing raw [b]HTML[/b] or any other code
Including line breaks </a>[/textarea]
< here and > here and
</textarea>
<div id="vorschau"></div>
This question already has answers here:
Matching quote wrapped strings in javascript with regex
(3 answers)
Closed 2 years ago.
I have a question, how can add <span style="color: blue"> to text in quotes.
Example:
.. and he said "Hello, I am Nick"
Using regex I want to achieve this result:
.. and he said <span style="color: blue>"Hello, I am Nick"</span>
I want to know how I can do that with regular expressions. Goal is to apply color only to text inside the quotes.
Using .replaceWith() function you can add span tag between any text with quotes.
$(document).ready(function() {
$("h2"). // all p tags
contents(). // select the actual contents of the tags
filter(function(i,el){ return el.nodeType === 3; }). // only the text nodes
each(function(i, el){
var $el = $(el); // take the text node as a jQuery element
var replaced = $el.text().replace(/"(.*?)"/g,'<span class="smallcaps">"$1"</span>') // wrap
$el.replaceWith(replaced); // and replace
});
});
.smallcaps {
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>and he said "Hello, i am Nick" and "I am good"</h2>
Use String.prototype.replace() method:
var str = document.querySelector('div').textContent;
var reg = /(".*\")+/g
var s = str.replace(reg, function(m){
return '<span style="color:blue">'+m+'</span>';
})
document.querySelector('div').innerHTML = s;
<div>and he said "Hello, I am Nick", some extra</div>
You can use the String's .replace() function as follows:
(1) If you want to keep the quotes and have them inside the <span>:
var source = '---- "xxxx" ---- "xxxx" ----';
var result = source.replace(/"[^"]*"/g, '<span style="color:blue">$&</span>');
console.log(result);
$('#container').html(result);
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div id="container"></div>
Notes:
The [^"] sequence in the regular expression defines a set of characters that matches all characters other than a double quote. Therefore, [^"]* matches zero or more characters that are not a double quote.
The $& in the replacement string will be replaced with the matched characters.
(2) If you do not want to keep the quotes:
var source = '---- "xxxx" ---- "xxxx" ----';
var result = source.replace(/"([^"]*)"/g, '<span style="color:blue">$1</span>');
console.log(result);
$('#container').html(result);
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div id="container"></div>
The parentheses in the regular expression create a capturing group. (Notice that the quotes are not within the capturing group.)
The $1 in the replacement string will be replaced with the first capturing group.
(3) If you want to keep the quotes, but have them outside the <span>:
var source = '---- "xxxx" ---- "xxxx" ----';
var result = source.replace(/"([^"]*)"/g, '"<span style="color:blue">$1</span>"');
console.log(result);
$('#container').html(result);
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div id="container"></div>
Note: This is the same as #2, but the quotes are included in the substitution string, so they are put back in the result string.
If regex is not mandatory, then try this split-map-join as well
var text = document.getElementById( "el" ).innerHTML;
function transform(input)
{
return input.split("\"").map( function(item,index){ if( index % 2 != 0 ){ item = '<span style="color: blue">' + item; } return item }).join("");
}
document.getElementById( "el" ).innerHTML = transform(text)
<div id="el">
and he said "Hello, i am Nick"
</div>
'and he said "Hello, I am Nick"'.replace(/"Hello, I am Nick"/, '<span style="color: blue">$&</span>');
Let's say I have a text :
<p> hello world! </p>
and I am using a function that cut the text after 5 words and adds " ...show more"
I want the result to be like this :
hello ... show more
Because of the <p> tags what I get is this output :
hello ...show more
what I see when I inspect the element is this :
<p> hello </p> ...show more
I must mention that the text can be with <p> or without.
Is there a way to solve this problem ?
Is there a way to insert the added text inside the <p> tag ?
I need to mention that I need the <p> tags, I can't use strip tags function.
Thanks,
Yami
Do you mean this?
var text = "<p>hello world</p>";
var res = "<p>" + text.substring(3, 8) + " ...show more</p>";
It results in:
<p>hello ...show more</p>
The way I see it, you have two options:
.split() the string by spaces (assuming a space separates words) then slice the first (up to) 5 elements. If there are greater than 5 element, add "...read more"; if not, it's unnecessary.
You can use some regex replace and (with a negative lookahead) ignore the first 5 words, but replace all other text with your "...read more". (I personally find this one having more overhead, but you could probably use (?!(?:[^\b]+?[\b\s]+?){5})(.*)$ as a pattern)
Having said that, here's what i mean with a string split:
function readMore(el){
var ary = el.innerHTML.split(' ');
el.innerHTML = (ary.length > 5 ? ary.slice(0,5).join(' ') + '... read more' : ary.join(' '));
}
var p = document.getElementById('foo');
readMore(p);
Assuming of course, for the purposes of this demo, <p id="foo">Hello, world! How are you today?</p> (which would result in <p id="foo">Hello, world! How are you...read more</p>)
$('p').text($('p').text().replace('world!', '... show more'));
I need to select a text using javascript that is between round brackets, and wrap it all in a span:
<p>Just some text (with some text between brackets) and some more text</p>
should become:
<p>Just some text <span class="some-class">(with some text between brackets)</span> and some more text</p>
I think something like this should be possible using regex, but i'm totally unfamiliar with using regex in javascript. Can someone please help? Thanks!
This should do the trick (str is the string holding the text you want to manipulate):
str.replace((\([^()<>]*\)), "<span class=\"some-class\">$1</span>");
It disallows (, ), < or > within the parenthesis. This avoids nesting issues and html tags falling in the middle of the parenthesis. You might need to adapt it to meet your exact requirements.
Since you're new to regular expressions, I recommend reading http://www.regular-expressions.info/ if you want to learn more.
oldString = '<p>Just some text (with some text between brackets) and some more text</p>';
newString = oldString.replace(/\((.*?)\)/g, '<span class="some-class">($1)</span>');
Try this:
<p id="para">Just some text (with some text between brackets) and some more text</p>
<input type="button" value="Change Text" onclick="ChangeText()"/>
<script>
function ChangeText()
{
var para = document.getElementById("para");
var text = para.innerHTML;
para.innerHTML = text.replace(/(.*)(\(.*\))(.*)/g, "$1<span class=\"some-class\">$2</span>$3")
}
</script>
Using RegExp object:
var str = "<p>Just some text (with some text between brackets) and some more text</p>";
var re = new RegExp("\(+(.*)\)+", "g");
var myArray = str.replace(re,"<span class="some-class">($1)</span>" );
Using literal:
var myArray = str.replace(/\(+(.*)\)+/g,"<span class="some-class">($1)</span>")