I'm getting the following raw string from a JSON file. I console.log it display fine.
"Hello, my name is Jane, from "IStaff" company.\r\n\r\n.We are interested in your service.\r\n\r\n.Please call me back "
When I rendering this string, there is no new lines.
the best way in my case is just add in css : white-space: pre-wrap;
If you insert that string into HTML, it will render by literally showing the \n and \r elements:
const string = 'Hello, my name is Jane, from "IStaff" company.\r\n\r\n.We are interested in your service.\r\n\r\n.Please call me back';
document.write(string);
You need to replace them with HTML <br> elements:
const string = 'Hello, my name is Jane, from "IStaff" company.\r\n\r\n.We are interested in your service.\r\n\r\n.Please call me back';
const renderString = string.replace(/(?:\r\n|\r|\n)/g, "<br>");
document.write(renderString);
Regex above from this answer.
I think this problem occurs when you use innerHTML, use <br/> instead of /r/n.
Example:
"Hello, my name is Jane, from 'IStaff' company.<br/> <br/> .We are interested in your service.<br/> <br/> .Please call me back "
"Hello, my name is Jane, from 'IStaff' company. .We are interested in your service. .Please call me back "
Whitespace characters like newlines do not render in HTML. You have to change the \n into <br>
function nl2br(str, is_xhtml) {
if (typeof str === 'undefined' || str === null) {
return '';
}
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
dataReceveid = function(json) {
$("div").html(nl2br(json.str));
}
$(function() {
dataReceveid({
str: '"Hello, my name is Jane, from "IStaff" company.\r\n\r\n.We are interested in your service.\r\n\r\n.Please call me back "'
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
The browser doesn't know what does it means \r\n. The language the web browser know only is HTML and \r\n is not an HTML language word. To break the line in the browser you have to use HTML language tag <br /> so the browser can consider it and break the lines.
So the simple solution to your problem is replacing \r\n with <br /> HTML tag/element.
Related
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.
I am using JS to remove/replace characters from a Page Title to show the slug/url as
function convertToSlug(Text){
return Text
.toString()
.trim()
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^\w\-]+/g, "")
.replace(/\-\-+/g, "-")
.replace(/^-+/, "")
.replace(/-+$/, "");
}
This will convert a page title of This is a page title | Company Name to this-is-a-page-title-company-name but how can I remove all text to the right of the | so that the returned slug is this-is-a-page-title?
Please note that the company name will change and just removing the whole part of | Company Name isn't sufficient. I need it to apply to any version of the title to the right of |.
Replace the pipe symbol (|), and everything after it with an empty string:
function convertToSlug(Text){
return Text
.replace(/\|.*/, '')
.trim()
.toLowerCase()
.replace(/\s+/g, '-');
}
console.log(convertToSlug('This is a page title | Company Name'));
assuming that you are using | char as seperator, you can use following:
function convertToSlug(Text){
return Text
.split('|')[0]
.trim()
.toLowerCase()
.replace(/\s/g,"-");
}
Late reply, but could be useful to someone else.
<input type="text" id="txtInput" />
<input type="button" onclick="return convertToSlug();" value="Remove text to the right of a character in JS
">
<script>
function convertToSlug(){
var Text = document.getElementById("txtInput");
var purgeCharPosition = Text.indexOf("|");
return Text
.toString()
.trim()
.substr(purgeCharPosition)
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^\w\-]+/g, "")
.replace(/\-\-+/g, "-")
.replace(/^-+/, "")
.replace(/-+$/, "");
}
</script>
I have a JavaScript function that looks like this:
function onAfterTranslate(item, translator) {
var thing = item.translated_text;
document.myform.keywords.value = "Translated Text:\r\n\r\n" + thing.replace(/<br>/g, "\r\n");
}
The parameter named item is an object, which includes an property called translated_text.
These are the contents of this variable:
mono <br> toro <br> gato <br> perro <br> elefante
What I want to do is convert the br tags to newline characters. (Ideally, it should look for optional spaces immediately before and after the br tag, and it should also accept any of the valid formats of br tag that exist, but that's not crucial at the moment.)
However, the replace command in the above code is not working, and I can't work out why.
If I remove the replace command so the line ends with the variable name thing, then it behaves as expected, updating the textarea box in my form with the correct value.
Even if I try replacing the letter "o" with an asterisk, it still doesn't work, which would suggest I'm doing something fundamentally wrong here.
Any suggestions?
You can use \s to look for spaces and ? for "preceding char may occur once or not". The regex is here below.
/\s?(<br\s?\/?>)\s?/g
Here below is an example with all possible br tags: <br>, <br /> and <br/> with some spaces in between.
var input = document.getElementById('input').value;
console.log(input);
document.getElementById('output').value = input.replace(/\s?(<br\s?\/?>)\s?/g, "\r\n");
textarea {
width: 400px;
height: 100px;
}
<h3>input</h3>
<textarea id="input">
fooo <br> bar <br> lorum ipsum dolor.
valar durum <br /> kel alar fol <br /> durom <br />.
a bread of kebab is tasteful !<br/>
EOL
</textarea>
<hr />
<h3>output</h3>
<textarea id="output"></textarea>
try
var text = "mono <br> totono <br> gato <br> elefante"
console.log( text.split( "<br>" ).join( "\n" ) );
and for trimming white spaces
text.split( "<br>" ).map( function(val){ return String(val).trim(); } ).join( "\n" );
for putting this in a textarea
document.body.innerHTML += "<textarea>" + text.split( "<br>" ).map( function(val){ return val.trim() } ).join( "\n" ) + "</textarea>" ;
So, it turns out the replace function was essentially fine (but enhanced now thanks to your contributions) - it was the format of the input data that was not what I was expecting.
I thought that the variable item.translated_text was an array element (because when I echoed it to the screen, I saw the value I was expecting), but it turned out it was actually an array, as I found out when I displayed the length of the variable and found it was only 1.
I now suspect that the item variable was a JSON construct and not a regular array, as I first thought.
Sorry if I wasted anyone's time on this.
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?
Hi this does not make sense I am trying to get put \n to break my sentence but it seems not working ,my code below
"Address:"+location.addressLine1 + " " + location.addressLine2 +"\n "+"Store Name:\n"+ location.storeName +" "+"Geofence:\n"+ location.maxGeofence+" "+"City:\n"+location.city
my goal is to have all the rows in new line ,Like below
Address:xxxxxxx
Store Name:xxxxxx
Gofence:xxxxxx
City:xxxxxxx
but I keep on getting
Address:xxxxxxx Store Name:xxxxxx Gofence:xxxxxx City:xxxxxxx
Either use <br/> in HTML or, if you wish to keep using \n, use the nl2br function from php.js :
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
This will convert every \n to a <br/>
Instead of using \n, use <br/>
<br /> is HTML element for a line break. <br /> allows to show up as a new line when HTML is rendered in a browser.
In html \n has no effect. Replace it with <br/> or place your code inside <pre> tags.
br - will make a new line inside HTML
pre - code inside will be formated as it was inside a text file (it will understood \n), but you will have to style it.
Here is solution for newline
"Address:"+location.addressLine1 + " " + location.addressLine2 +"<br>"+"Store Name:<br>"+ location.storeName +" "+"Geofence:<br>"+ location.maxGeofence+" "+"City:<br>"+location.city
Note : \n is work only php not in Html so \n will not work here.