How to insert a line break in createTextNode - javascript

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 />');

Related

txt.replace </blockquote> in textarea js

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.

Remove HTML tags and formatting text

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!

Removing span tags issue if text has encoded characters

I'm looking to remove span tags that wrap blocks of text in an in-browser editor but am having trouble if the text contains any sort of special characters like newline '\n' or encoded characters like , • , etc.
Here's my code that works on sentences without encoded characters
function fnIgnoreThisErr(evtTargID){
// use the passed parameter
var errIdx = evtTargID.substr(evtTargID.indexOf('err-') + 4);
// buld span tag for finding
var errSpan = "span.err-" + evtTargID;
// declare the editor
var editor = CKEDITOR.instances.editor1;
// get text from the editor
var edata = editor.getData();
// find the specific span in the text
var spanData = $( edata ).find(errSpan);
// get outerHTML and innerText to use for replacement
var myCurrText = spanData[0].outerHTML;
var myNewText = spanData[0].innerHTML;
// standard js replace works if no special chars
var replace_text = edata.replace(myCurrText, myNewText); //
// sets the data back in CKEditor
editor.setData(replace_text);
}
Here's an example of the text with the span tag
myCurrText:
<span class=\"vts-warn vts-ParseFailure err-2\">Approval of ICA<br />\n GAMA requested further clarification of proposed §§25.1739 (now §25.1729) and 25.1805(b) (now §26.11(b)) requirements that ICA prepared in accordance with paragraph H.</span>
And with the span tag removed.
Approval of ICA<br />\n GAMA requested further clarification of proposed §§25.1739 (now §25.1729) and 25.1805(b) (now §26.11(b)) requirements that ICA prepared in accordance with paragraph H.
It works great on plain sentences without any encoded characters. I can switch to jQuery but couldn't get replaceWith to work either.
What am I missing here?
I figured it out. There appears to be a discrepancy between html entities and the way they are being rendered/interpreted by the browser and my JS.
i.e. The outerHTML of the span is not a character-for-character match of the text in edata.
So I just get the indexOf value for the start of the span and the length of the span node. However, due to the discrepancy mentioned, this length may include additional characters. So, next, I find the exact position of the '' tag. From there, I build a string variable that exactly matches the text that needs to be replaced.
Here's my final code. (I kept it long-form for clarity)
function fnIgnoreThisErr(evtTargID){
// use the passed parameter
var errIdx = evtTargID.substr(evtTargID.indexOf('err-') + 4);
// buld span tag for finding
var errSpan = "span.err-" + evtTargID;
// declare the editor
var editor = CKEDITOR.instances.editor1;
// get text from the editor
var edata = editor.getData();
// find the specific span in the text
var spanData = $( edata ).find(errSpan);
// extract the span class name
var spanTag = '<span class="'+spanData[0].className+'">'
// find indexOf value for the span opening tag
var spanPos = edata.indexOf(spanTag);
// get the initial length of the span.
var spanLength = spanData[0].outerHTML.length;
// get the actual text from that span length.
var spanString = edata.substring(spanPos,spanPos+spanLength);
// find the acutal position of the span closing tag
var spanClose = spanString.indexOf('</span>');
var spanTagClosePos = spanClose+7;
// extract the true text comprising the span tag
var spanStringMod = edata.substring(spanPos,spanPos+spanTagClosePos);
var spanInnerHtm = spanData[0].innerHTML;
log("errSpan: "+ errSpan);
log("errSpanClass: "+ errSpanClass);
log("spanData: "+ JSON.stringify(spanData));
log("spanPos: "+ spanPos);
log("spanTagClosePos: "+ spanTagClosePos);
log("spanStringMod: "+ spanStringMod);
log("spanInnerHtm: "+ spanInnerHtm);
var newEdata = edata.replace(spanStringMod, spanInnerHtm);
log(" newEdata: "+ newEdata);
// update the editor
editor.setData(newEdata);
}
I hope this helps someone, somewhere, at some time!
Cheers!

Converting HTML to JavaScript string in PhpStorm

I'd like to convert some html easily into concatenated JS strings in PhpStorm.
From:
<div class="spa-shell-head">
<div class="spa-shell-head-logo"></div>
<div class="spa-shell-head-acct"></div>
<div class="spa-shell-head-search"></div>
</div>
To:
var main_html = ''
+ '<div class="spa-shell-head">'
+ ' <div class="spa-shell-head-logo"></div>'
+ ' <div class="spa-shell-head-acct"></div>'
+ ' <div class="spa-shell-head-search"></div>'
+ '</div>';
Ideally into the other direction as well. Is there any chance to achieve this? With a plugin? I could imagine that a macro with some regex could do it. Is it possbile?
Same question for other IDE can be found here. Or here.
Using only PHPStorm, you can use the Extra Actions plugin:
Select all your lines
Split the selection into lines (ctrl + shift + L)
Go to the beginning of the line (home)
Add a plus sign and a quote
Go to the end of the line (end)
Add a quote
Rather than converting HTML to a JS string, you should really create your elements in JS and then insert them into the DOM. This would give you much more control, not create such a difficult to maintain/read code, cause less problems, and be much faster to boot:
var outerDiv = document.createElement("div"); // Create a div
outerDiv.className = "spa-shell-head"; // Give it a class
var innerDivLogo = document.createElement("div");
innerDivLogo.className = "spa-shell-head-logo";
var innerDivAcct = document.createElement("div");
innerDivAcct.className = "spa-shell-head-acct";
var innerDivSearch = document.createElement("div");
innerDivSearch.className = "spa-shell-head-search";
outerDiv.appendChild(innerDivLogo); // Append into original div
outerDiv.appendChild(innerDivAcct);
outerDiv.appendChild(innerDivSearch);
document.body.appendChild(outerDiv); // Add to page
The above creates the following:
https://jsfiddle.net/yfeLbhe4/

How to copy to clipboard using JavaScript but also keep newline character ('\n')

In my helper app I'm trying to take prototype work in Ipython and quickly turn it into a script (for when it works). I have a working clipboard function thanks to Click button copy to clipboard, on this page:
http://jsfiddle.net/codyc54321/udxp4osm/1/
While it does copy to clipboard, it comes out as a rambling string like
match = re.match(in_rgx, string)match#<_sre.SRE_Match at 0x7f90674cf3d8>match.gromatch.group match.groupdict match.groups match.group()#'In [3]: '
instead of what I see on the page:
match = re.match(in_rgx, string)
match
#<_sre.SRE_Match at 0x7f90674cf3d8>
match.gro
match.group match.groupdict match.groups
match.group()
#'In [3]: '
and there is no newline separation. For some reason my fiddle isn't actually copying, but my app is, but what happens is I used a Django filter to turn my newlines (\n) into <br> tags:
<p id="clean-code">match = re.match(in_rgx, string)<br /><br />match<br />#<_sre.SRE_Match at 0x7f90674cf3d8><br /><br />match.gro<br />match.group match.groupdict match.groups <br /><br />match.group()<br />#'In [3]: '<br /></p>
and when I hit "copy to clipboard", get that string, with no br tags or newline. So if I paste into Atom, Gedit, any text editor, I get one long line which renders my page useless. I tried putting a real '\n' after each line, and as you can imagine that just added a new line. I tried putting the literal \n text, and then I get:
match = re.match(in_rgx, string)\nmatch\n#<_sre.SRE_Match at 0x7f90674cf3d8>\nmatch.group()\n#'In [3]: '\n
as one line, which makes sense. Here is my current Python with the superfluous \n:
def clean_ipython_line(code_line):
in_rgx = r"^In \[\d+\][:] "
out_rgx = r"^Out\[\d+\][:] "
in_match = re.match(in_rgx, code_line)
out_match = re.match(out_rgx, code_line)
if in_match:
line = code_line.replace(in_match.group(), '') + '\\n'
return line
elif out_match:
line = ('#' + code_line.replace(out_match.group(), '')) + '\\n'
return line
else:
return code_line
def clean_ipython_block(unclean_code):
unclean_lines = unclean_code.split('\r\n')
cleaned_lines = []
for dirty_line in unclean_lines:
cleaned_lines.append(clean_ipython_line(dirty_line))
clean_block = "\r\n".join(cleaned_lines)
print(clean_block)
return clean_block
Is there a built in JavaScript way to copy to clipboard turning those br tags into the real newline character that will break these lines when I paste into editor?

Categories

Resources