I give up! I looked at many different answers. I've tried many different ways and nothing works. I want to change the </blackquote> tag to <br /> or a new line in the textarea. Alternatively, change to some other character, because later I can replace another character in PHP to <br/>. How to do it?
Working example for easy understand here: https://jsfiddle.net/jsf88/rb3xp7am/35/
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎 </blockquote><br />
"X" -- HERE I want BR_TAG or new line in textarea after click 'quote' 😐
</div>
</section>
$(document).on('ready', function() {
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').text();
//txt = txt.replace('</blockquote>', '<br/>');
//txt = txt.replace(/<\/(blockquote)\>/g, "<br/>");
//txt = txt.replace(/blockquote*/g, '<br/>');
//txt = txt.replace(/(.*?)<\/blockquote>(.*?)/g, ' xxx ');
txt = txt.replace(/<\/blockquote>/gi, '<br/>')//NOT WORKING!!
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');//working great
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]'));
});
});
To make it funnier, another example with changing the blackquote tag to br works without a problem. Why? can someone explain it?
//OTHER EXAMPLES WHERE CHANGE </BLACKQUOTE> to <br/> WORKING GOOD... WTF?!
string = ` <blockquote>this is a quote for comment😎 </blockquote><br />"X" -- HERE I want BR_TAG or new line in textarea after click 'quote' 😐`;
string = string
.replace(/<\/blockquote>/gi, ' <br /> ');//but here working! ;/
console.log(string);
you recover text with text function ('.replyMsg').text() but in that case you will have the text but with no html tag like <blockquote> so first you will have to recover the html to have the blockquote tag
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
the br tag is not interpreted in textarea so you have to change it by a new line character
don't forget to remove opened bloquote tag to get the expected result
txt = txt.replace(/<blockquote>/gi, '');
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');
txt = txt.replace(/<\/blockquote>/gi, '\n');
txt = txt.replace(/<blockquote>/gi, '');
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]'));
});
blockquote {
background-color: silver;
}
.replyMsg {
border: 2px solid green;
}
.quoteMsg {
background-color: green;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎 </blockquote>
"X" -- HERE I want BR_TAG or new line in textare a after c lick 'quote' 😐
</div>
</section>
The first problem in your code was how you were adding the event listener to the ready event. Being it something invented by jQuery, and not a native event, the correct way to do it should be as of now (v.3.3.1 the version I used in this demo) $(document).ready(()=>{/*code here*/}).
As a further reference:
https://api.jquery.com/ready/
There is also $(document).on( "ready", handler ), deprecated as of
jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes
ready before this event is attached, the handler will not be executed.
But... it's not perfectly clear how did you wish to transform your text before setting the value of the textarea. So I just better factored your logic so that you have some clear steps:
grabbing the blockquote element text content and trimming it (being the origin)
applying the transform newline to whitespace (with the regex that I left untouched)
build the final string as a template literal that will include the quote content, the meta tags wrapping it, AND anything else you wish to add like for example a new line (\n) that in this example is exacerbated by a text following it.
There's a hint in your words that put me in the position to say something superflous but still deserving an attempt: the value of a inner text is just plain text and doesn't render html content. So the <br> itself would remain as you read it and wouldn't have any rendering effect on the textarea content. That's why I focused my demonstration on putting a newline with the escaping sequence. It works both on double quoted strings and template literals: "\n" `\n`
Further notes
It seems the original approach of processing the blockquote html was preferred. It's worth saying that it was appearently a terrible strategy for several reasons:
It grabs the blockquote content as html despite that's not how it's
rendered on the page.
It takes the effort to consider the whole outerHTML removing the
wrapping blockquote tags instead of fetching directly the innerHTML.
It adds the newline as newline instead of embedding it as <br> so
at this point I ask myself if the content in the textarea was
supposed to be encoded html or not.. and the added br would then
belong to something meta?
It's harder to deal with in case you want to further customize the
string processing
But... maybe there's something I didn't get and I'm doing weak assumptions.
//since you are using the ready event with jquery, that's the correct syntax
$(document).ready(function() {
$('.quoteMsg').click(function() {
//grabs the text content of the blockquote element (trimming it)
var quoteTextContent = $(this).closest('.replyBox').find('.replyMsg').text().trim();
//performs the transform already in place in your code.. replacing newlines with white spaces
quoteTextContent = quoteTextContent.replace(/(?:\r\n|\r|\n)/g, ' '); //working great
//builds the string to set the textarea value with, using a template literal
//here you can add anything you want.. like a new line but that's just an example
const encoded = `[quote]${quoteTextContent}[/quote]\nand something following to show the new line happening`;
console.log(encoded);
$("textarea[name='quote']").val( encoded );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎
<br>
Having new lines also ... since you perform a regex transform newline=>whitespace
</blockquote><br />
</div>
</section>
Well, thanks for answers. The problem was a missing .html tag.
This script work for me almost perfect for quoting few times:
$(document).on('ready', function() {
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');
txt = txt.replace(/</g, "<");
txt = txt.replace(/>/g, ">");
txt = txt.replace(/&/g, "&");
txt = txt.replace(/"/g, '"');
txt = txt.replace(/'/g, "'");
txt = txt.replace(/<br>/g, "");
txt = txt.replace(/<hr>/g, "[hr]");
//txt = txt.replace(/<hr>/g, "\n");
txt = txt.replace(/<blockquote>/gi, '');
txt = txt.replace(/<\/blockquote>/gi, '[hr]');
txt = txt.replace(/[hr][hr]/gi, "");//not working ([][])
txt = txt.replace(/[hr][hr]/gi, "[hr]");//not working ([[hr]][[hr]])
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]\n'));
});
});
The problem here is I dont know how to change dubble [hr][hr] for nothing, because this txt = txt.replace(/[hr][hr]/g, ""); not working, so would be cool for more explain about. One more time big thanks for answers! this function .replace is not as intuitive as in PHP.
EDIT: ahh.. I think is not possible to delete this dubel, because I extra insert it two times. Nvm. I will find and del this dubel in PHP.
Related
I would like to remove HTML tags between text and change newline to space. I'm using this pattern below but it is not perfectly. It adds two or more space between text. How to fix this pattern?
replace(/( |<([^>]+)>)/ig, ' ');
try below code and check
replace(/(<([^>]+)>)/ig,"");
UPDATE
You can do this way,
var html = 'Example: <h1></h1><p></p><div> </div><div>CONTENT</div> ';
html = html.replace(/\s|\n| /g, ' ');
html = html.replace(/<[^>]+>/gm, '');
Output will be like this,
Example: CONTENT
Play around the above solution & you will succeed.
Here is how I'll do what you want:
(See comments in my snippet)
// Input data
var input_data = `My<div><br>
<span></span>
<span></span>
</div><p>Content</p>`;
console.log("Input:", input_data);
// Creates html element with Input data
var elm = document.createElement('div');
elm.innerHTML = input_data;
// Use native function '.innerText' to get rid of the html,
// then replace new lines by spaces, and multiple spaces by only one space
output_data = elm.innerText.replace(/\n/g, ' ').replace(/[\s]+/g, ' ');
console.log("Output:", output_data);
Hope it helps!
I'm to build a forum for the project, but right now I'm facing this problem where I want users to be able to post their HTML source code as it works in this forum.
But the problem is that the code runs or scatters my design when retrieve from my DB.
I tried using repalce() in jQuery but I could only replace < with < but I want a function to be able to replace others such as >,",' and & so my question is how can I update this function.
function convert(div){
var str = $(div).html();
var str2 = str.replace(/</g,"<");
var sta = $(div).html(str2);
return sta;
}
The above code work to replace the < but when I try including >,",' and & in the function it will stop work how can i make it work.
Thanks in advance.
Stick it in <pre> or <code> tags, or both, and make sure you use text() when inserting the content to the tag
function convert(div){
var str = $(div).html();
var sta = $('<code />', {text : str});
return sta;
}
var result = convert( $('#test') );
$('#result').html(result)
#result {
white-space : pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<span>
<p>TEST</p>
</span>
</div>
<br />
<div id="result">
<code> will preserve the code, and <pre> will preserve whitespace, but there's also the CSS white-space property, that can act as a <pre> tag using the pre setting
For a little program that outputs some XML Code in a p element I need to have some line breaks in the output.
In the last week I tried a lot of things like document.createElement("br"); or inserting escape character \n or unicode whitespace-character \u000A but nothing worked.
My output now:
<viva:form rdf:parseType="Resource"> <viva:title>55</viva:title>
I need it that way:
<viva:form rdf:parseType="Resource">
<viva:title>55</viva:title>
My code:
var vivaTitle;
function elementeAbrufen() {
vivaTitle = document.getElementById("inputVivaTitle").value;
var p = document.createElement("p");
var t = document.createTextNode(headErzeugen());
p.appendChild(t);
document.body.appendChild(p)
}
function headErzeugen() {
// insert unicode lf
var lf = "\u000A";
var xmlHeadStruktur = "<viva:form rdf:parseType=\"Resource\">";
var xmlHeadTitle = "<viva:title>" + vivaTitle + "</viva:title>";
return xmlHeadStruktur + lf + xmlHeadTitle
}
<p id="vivaTitle" title="">viva:title:
<input type="text" id="inputVivaTitle" value="">
<button onclick="elementeAbrufen()">send</button>
I'm thankfull for every help.
Cheers, Didier
Using \n works fine. Here's a jsfiddle:
https://jsfiddle.net/Lftqy9b0/1/
var text = document.createTextNode("Hello\u000aWorld");
document.body.appendChild(text);
document.body.style = "white-space: pre;"
'\n', '\u000a', etc. should all be valid, but I recommend using '\n'. Most people will recognize it better.
The reason this isn't working for you is that HTML collapses all whitespace. So even though the text node DOES contain a newline, it's just the same as a newline typed into HTML (those are text nodes too.)
You can see in the above snippet that I included a 'white-space: pre;' rule. This causes it not to collapse whitespace. See here for more options:
https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
If you're formatting raw text for display like this, that's probably the easiest way. Of course, you should put the white-space rule in a separate css file.
Does this work?
var t = document.createTextNode(headErzeugen() + '<br />');
I currently have a little HTML window I use at work to automatically Capitalize All, Alphabetize, and Capitalize first letters of contents entered into a <TextArea> on the HTML. I was hoping to find a method to add an additional "Comma" Button (<input type="submit">) - so it will automatically add a comma to the end of each line in the <TextArea>.
This should do what you are trying to accomplish.
function comma(){
var textarea = document.getElementById('textarea').value;
var res = textarea.replace(/(\r\n|\n|\r)/gm,",\r\n");
console.log(res);
document.getElementById('textarea').value = res;
}
textarea {
width: 500px;
height: 500px;
}
<textarea id="textarea"></textarea>
<button onclick="comma()">Comma</button>
Steps
Put the content of the textarea in a variable, say 'textareaContent'
Find all occurrences of "\r\n" and replace with ";\r\n"
EDIT.
HTML + JS
<script>
function addComma()
{
// get textarea's content
var content = document.getElementById('myTextArea').value;
// replace all newline's with ';\n'
var replaced = content.replace(/\n/g,';\n');
// rewrite the content with the new content
document.getElementById('myTextArea').value = replaced; }
</script>
<textarea id='myTextArea' rows='5' cols='30'>
First Line
Second Line
Third Line
</textarea>
<input type='button' onclick='addComma()' value='Add Comma' />
Anyways, this is an example, in live action. See the fiddle here -- http://jsfiddle.net/u6b7yz21/
Cheers.
I have an editable div where the user writes. As he writes, a javascript function adds the div html to a textarea. When the user presses SHIFT+Enter, the div gets a <br>. This is good.
But when the user presses Enter alone, the div gets <div></div> tags.
Therefore I try to make it so that when Enter is pressed, javascript scans the div's html to eliminate the </div> and change the <div> for <br>. The result will be that regardless of whether the user presses SHIF+Enter or Enter, the div's html will end up using only <br> for linebreaks.
<head>
<script type="text/javascript">
function doStuff(e){
if (window.event.keyCode == 13) {
var s=document.getElementById("divv").innerHTML;
s.replace("<div>", "<br>");
s.replace("</div>", "");
document.getElementById("divv").innerHTML=s;
}
document.getElementById("txtt").value = document.getElementById("divv").innerHTML;
}
</script>
</head>
<body>
<div contenteditable="true" id="divv" onKeyUp=doStuff(event);">
write here! Then press enter!
</div>
<textarea id="txtt" rows="30" cols="100">
</textarea>
</body>
My code doesn't work. When Enter is pressed, The textArea still shows div tags.
I'm not sure what I'm doing wrong. Please help.
The replace() method does not modify the string it's called on, it returns a new string with the occurrences replaced.
You can do something like:
var divv = document.getElementById("divv");
divv.innerHTML = divv.innerHTML.replace("<div>", "<br>").replace("</div>", "");
Usually browsers will have innerHTML store tags as <DIV> and </DIV> - you could try using:
s = s.replace(/<div>/ig,"<br>");
s = s.replace(/<\/div>/ig,"");
Firstly, if you use xhtml, you must use tag "< br / >".
Also draw attention on str.replace: it replaces only once.
js> var x = "hello";
js> x.replace("l", "L");
heLlo
Make your replace implementation:
js> function myreplace(str, pattern, change_to) {
var s = str;
var s2 = s;
do {
s2 = s;
s = s.replace(pattern, change_to);
} while (s2 != s);
return s;
}
js> myreplace("helllllo", "l", "L");
heLLLLLo