Javascript Replace doesn't work because of Escape Sequence - javascript

I need to replace every '\n' in a var with a <br> tag but the code I tried doesn't work. Here's my example and code:
Example:
Hello there \n Are you online? \n What do you mean?
Should become:
Hello there <br> Are you online? <br> What do you mean?
Code:
var text = 'Hello there \n Are you online? \n What do you mean?';
var find = '\n';
var re = new RegExp(find, 'g');
re = text .replace(re, '<br>');
What am I doing wrong?

var text = 'Hello there \n Are you online? \n What do you mean?';
var find = '\n';
var re = new RegExp(find, 'g');
re = text.replace(re, '<br>');
document.write(re);
Works fine

Working Fiddle
In your fiddle (which you did not post in your original question) there are several issues addressed already in the comments. But the crux of your problem -- that would have helped us help you faster -- is that you're pulling a string with "\n" from an innerHTML property. Those are not newline characters, because if you're seeing a literal "\n" instead of a newline, it means it has been escaped. Therefore, you need to use "\\n" in your regular expression, not "\n". Use the devtool consoles in modern browsers to inspect your variables and catch errors.
Code:
var el = document.getElementById("ado")
var text = document.getElementById("ado").innerHTML;
text = text.replace(/\\n/g, '<br>');
el.innerHTML = text

in your fiddle you wrote :
document.findElementById
instead of
document.getElementById
I think it is one of things that should solve your issue !

Related

How to add a new line in MySql when user hits 'enter' in textarea? [duplicate]

How can I read the line break from a value with JavaScript and replace all the line breaks with <br /> elements?
Example:
A variable passed from PHP as below:
"This is man.
Man like dog.
Man like to drink.
Man is the king."
I would like my result to look something like this after the JavaScript converts it:
"This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."
This will turn all returns into HTML
str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');
In case you wonder what ?: means.
It is called a non-capturing group. It means that group of regex within the parentheses won't be saved in memory to be referenced later.
You can check out these threads for more information:
https://stackoverflow.com/a/11530881/5042169
https://stackoverflow.com/a/36524555/5042169
If your concern is just displaying linebreaks, you could do this with CSS.
<div style="white-space: pre-line">Some test
with linebreaks</div>
Jsfiddle: https://jsfiddle.net/5bvtL6do/2/
Note: Pay attention to code formatting and indenting, since white-space: pre-line will display all newlines (except for the last newline after the text, see fiddle).
Without regex:
str = str.split("\n").join("<br />");
This works for input coming from a textarea
str.replace(new RegExp('\r?\n','g'), '<br />');
If the accepted answer isn't working right for you then you might try.
str.replace(new RegExp('\n','g'), '<br />')
It worked for me.
Shortest code supporting the most common EOL styles \r, \n, \r\n and using HTML5 <br>:
s.replace(/\r?\n|\r/g, '<br>')
Regardless of the system:
my_multiline_text.replace(/$/mg,'<br>');
It is also important to encode the rest of the text in order to protect from possible script injection attacks
function insertTextWithLineBreaks(text, targetElement) {
var textWithNormalizedLineBreaks = text.replace('\r\n', '\n');
var textParts = textWithNormalizedLineBreaks.split('\n');
for (var i = 0; i < textParts.length; i++) {
targetElement.appendChild(document.createTextNode(textParts[i]));
if (i < textParts.length - 1) {
targetElement.appendChild(document.createElement('br'));
}
}
}
This worked for me when value came from a TextBox:
string.replace(/\n|\r\n|\r/g, '<br/>');
For those of you who just want to allow max. 2 <br> in a row, you can use this:
let text = text.replace(/(\r?\n){2,}/g, '<br><br>');
text = text.replace(/(\r?\n)/g, '<br>');
First line: Search for \n OR \r\n where at least 2 of them are in a row, e.g. \n\n\n\n. Then replace it with 2 br
Second line: Search for all single \r\n or \n and replace them with <br>
if you send the variable from PHP, you can obtain it with this before sending:
$string=nl2br($string);
It will replace all new line with break
str = str.replace(/\n/g, '<br>')
If you want to replace all new line with single break line
str = str.replace(/\n*\n/g, '<br>')
Read more about Regex : https://dl.icewarp.com/online_help/203030104.htm
this will help you everytime.
Not answering the specific question, but I am sure this will help someone...
If you have output from PHP that you want to render on a web page using JavaScript (perhaps the result of an Ajax request), and you just want to retain white space and line breaks, consider just enclosing the text inside a <pre></pre> block:
var text_with_line_breaks = retrieve_some_text_from_php();
var element = document.querySelectorAll('#output');
element.innerHTML = '<pre>' + text_with_line_breaks + '</pre>';
I had a config in PHP that was being passed in from the Controller. (Laravel)
Example: PHP Config
'TEXT_MESSAGE' => 'From:Us\nUser: Call (1800) 999-9999\nuserID: %s'
Then in javascript using es6 reduce. notice I had to have two \\ or the output was not being replace correctly. Here are the parameters that are assoicated with the reduce function
previousValue (the value resulting from the previous call to
callbackfn)
currentValue (the value of the current element)
currentIndex Optional
array (the array to traverse) Optional
//p is previousVal
//c is currentVal
String.prototype.newLineReplace = function(){
return [...arguments].reduce((p,c) => p.replace(/\\n/g,c), this);
}
Here is how i used it in my script.
<script type="text/javascript">var config = #json($config);</script>
config.TEXT_MESSAGE.newLineReplace("<br />")
of course you could just called it on a javascript sring like...
let a = 'From:Us\nUser: Call (1800) 999-9999\nuserID: %s'
var newA = a.newLineReplace("<br />")
//output
'From:Us<br />User: Call (1800) 999-9999<br />userID: %s'

Why does getting value from data-attribute affect the text

I'm struggling with some syntax, mostly why the data-attribute(HTML5) is affecting the text in the way it is.
Please consider this example which does what is expected
<div id="s"></div>
<script>
var ele = document.getElementById("s");
var txt = "this is it \n and done";
ele.innerText = txt;
</script>
The result is I see 2 lines in HTML due to the \n. This is expected
The task means I need to change the way we work into
<div id="s" data-txt="this is it\nand done"></div>
<script>
var ele = document.getElementById("s");
var txt = ele.getAttribute("data-txt");
ele.innerText = txt;
</script>
Note we're now using the data attribute of data-txt. The issue is this renders the text verbatim, meaning I see 1 line: this is it\nand done
https://jsfiddle.net/he4ydvva/
The fact I can't even use replace (ele.getAttribute("data-txt").replace('\n','blah');) suggests that although I see \n, the computer is reading something different (maybe the charcode value or similar)
Why does this happen and how do I prevent it?
Edit
I have seen How can I insert new line/carriage returns into an element.textContent? but this won't suffice as I need the string to exist within the data-txt and concatenating as "this is " + String.fromCharCode(13) + " is not valid for HTML5
You are confusing HTML with JavaScript.
\n is a JavaScript character. data-* attributes are HTML. For inserting newline in HTML, you should use the HTML entity
(Newline) or 
 (carriage return) or their combination.
HTML doesn't understand \n, \r and so on.
Also note,
<div>This is a line \n Another one</div>
This won't insert newline but the code below will:
<div>This is a line
Another one</div>
Check out the full list of HTML entities
Here's what you should use:
ele = document.getElementById("t");
txt = ele.getAttribute("data-txt").replace(/\\n/g,'<br>');
ele.innerHTML = txt;
Explanation:
The \ char is an escape character and so to specify a new line, you need to use two \\ so that the 1st one escapes the meaning of the second. The second one is then treated as a normal char and is read together with the n as \n.
Further, you must replace that with a <br> because a browser will not respect CRLF chars.
Here is your example on jsfiddle fixed: https://jsfiddle.net/4eurrzgx/
var ele = document.getElementById("s");
var txt = "this is it \n and done";
ele.innerText = txt;
ele = document.getElementById("t");
txt = ele.getAttribute("data-txt").replace(/\\n/,'<br>');
ele.innerHTML = txt;
<div id="s"></div>
<p>
***
</p>
<div id="t" data-txt="this is it\nand done"></div>

How to write regex to remove whitespace between tag and words for HTMl minifier [duplicate]

This question already has answers here:
RegEx match open tags except XHTML self-contained tags
(35 answers)
Closed 7 years ago.
I am building a very simple HTML minifier. So far so good.
var file = process.argv[2],
html = "",
fs = require("fs");
html = fs.readFileSync(file, "utf8");
string = html.replace(/\n/g, "");
var x = string.replace(/[\t ]+\</g, "<");
var y = x.replace(/\>[\t ]+\</g, "><");
var z = y.replace(/\>[\t ]+$/g, ">");
console.log(z)
returns string: <div id="hello"><p class="new"> Hello</p></div>
How do I write a regex to get rid of any space that will appear between words and tags (before and after)? Should return: <div id="hello"><p class="new">Hello</p></div>
This should work for you:
var html = '<div id="hello"><p class="new"> Hello friend </p></div>';
var result = html.replace(/>\s+|\s+</g, function(m) {
return m.trim();
});
https://jsfiddle.net/5gbhhh25/
It will only remove spaces between a tag and a word (opening and closing). So it won't affect text in tags or spaces between text.
torazaburo makes a good point about a potential pitfall in OP's requirements where a single space is required to preserve the structure of the text. So Tushar's solution of str.replace(/\s+/g, ' '); would work perfectly in that case.
Replace any sequence of non-less-than-signs with a string which compresses multiple spaces within it to a single space:
str.replace(/[^<]+/g, function(match) { return match.replace(/\s+/, ' '); });
< "<div id="hello"><p class="new"> Hello</p></div>"
Of course, you don't want to get rid of the space before "Hello", because it is meaningful.
You can use the trim() method to get rid of empty space without regexp.
You can find an example on the W3Schooll web site
See :
var str = " Hello World! ";
alert(str.trim());

Replacing closing HTML tags with HTML tag + \n

I'm trying to replace generally closing html tags with the closing tag + a line break, i found similar posts here on SO, none really helped me to accomplish what I'm looking for.
</li> would be </li>\n
<img some property /> would be <img some property />\n
I managed to do that in php with the following funtion, which works well:
public static function addLBinHTML($htmlcode){
$pattern= array('~(</.*?>)~','(/>)');
$replace= array('${1} Hallo \n ','/>\n ');
return preg_replace($pattern, $replace, $htmlcode);
}
I'm trying to do the same in JavaScript / jQuery and I'm failing on getting the variable(in php regex ${1}).
I tried with .split .join and with .replace, and I think .replace is the right way to go.
Here is what I got (my last and hopefully closest attempt)
function setLinebreaks(taID){
var strContent = $('#'+taID).val();
var regex = new RegExp("</.*?>", "gi");
strContent.replace(regex, "${1} \n ")
.replace(/\/>/g,'/> \n ');
console.log(strContent);
$('#'+taID).val(strContent);
}
Thanks in advance for your help
You have to capture the regular expression with brackets, assign the replaced string and replace ${1} by $1:
var regex = new RegExp("(</.*?>)", "gi");
strContent = strContent.replace(regex, "$1 \n ")
.replace(/\/>/g,'/> \n ');
Or you can simply put the replace methods into the val function.

JS Regex .replace, what am I missing?

I'm trying to perform a simple regex replace in javascript to replace new lines \n with html breaks
var strings = 'Hello world
This is a test.
Multi-line.';
stringt = strings.replace( '/(\r\n|\n|\r)/gm', '<br />' );
alert(stringt);
Testing the RegEx pattern on a couple of online testers has proven successful, I guess I'm just missing something real dumb?
You can't define strings like that.
You can do multiline strings like this though
var str = "Hello world\n\
This is a test.\n\
Multi-line.";
Then this regexp will work for you
str.replace(/[\r\n]+/g, "<br>");
Notice that regexp in JavaScript are not enclosed in quotes " like they are in langs like PHP.
Per #alex's comment, you could create the regexp like this
var re = new RegExp('[\r\n]+', 'g');
str.replace(re, "<br>");
In this case, you use a string, but no / delimiters.

Categories

Resources