If using javascript convert /n to > - javascript

I have a piece of text that comes from the backend with /n string in it, but I hope I can replace this with
a lot of ways I found on the Internet, but I still can't replace it with a label smoothly, does anyone know the reason Caused?
Thanks for your help.
let demo = document.querySelector('.demo').textContent;
console.log(demo)
demo.replace(new RegExp('\r?\n','g'), '<br />');
<p class="demo">尚有 1 個職缺使用母公司的點數,\n關閉後才可解除綁定</p>

const demoEl = document.querySelector('.demo')
demoEl.innerHTML = demoEl.textContent.replace(/\\n/g, '<br />');
<p class="demo">尚有 1 個職缺使用母公司的點數,\n關閉後才可解除綁定</p>
A couple of points:
Your text doesn't include a new line character so you need to match for the character combination of \n like so... /\\n/g
Your just replacing the content reference, you need to apply the replace to the elements innerHTML

Related

How do I prevent the line from not breaking in a header of a page?(html) [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'

Repeat a javascript replace until no change is made?

I have a short but complex regular expression to trim spaces regardless of html tags present in the string.
var text = "<span><span>ex ample </span> </span>";
// trim from start; not relevant in this example
text = text.replace(/^((<[^>]*>)*)\s+/g, "$1");
// trim from end
text = text.replace(/\s+((<[^>]*>)*)$/g, "$1");
console.log(text);
<span><span>ex ample </span> </span> - example input
<span><span>ex ample</span></span> - expected output
<span><span>ex ample </span></span> - observed output
How do I achieve my expected output?
I've tried adding the /g flag because it should supposedly match more than once and that should fix it (running the replace twice does work for the example) but it doesn't seem to repeat anything at all.
Alternative ways to trim strings regardless of tags are also appreciated because that is my primary objective. The secondary objective is learning why this didn't work.
You need to add some meaning to your tags, some need their spaces, some don't.
Try this:
text.replace(/\s*(<\/?(span|div)>)\s*/g, "$1")
.trim()
.replace(/\s+/g, ' ');
It:
replaces spaces around tags "surrounding" content
trims spaces around global string
removes redundant spaces
The list of "surrounding" tags can be changed to include things like tr...
Steps 2 and 3 might come first to speed things up.
Tried it with:
var text = "<div> <i>ano</i> <b>ther</b> <span> <b>my</b> <i>ex</i> <u> ample </u> </span> </div>";
First answer, prior to comments.
The idea is to remove all spaces between:
a non-space character and an opening tag
a closing tag and a non-space character
text.replace(/([^\s])\s*(<)/g, "$1$2")
.replace(/([>])\s*([^\s])/g, "$1$2")
.trim();
Preamble: don't just copy this, read to the end.
Thinking from the other way around - by replacing until no match is found instead of until no change is made, this seems to work very simply.
var text = "<span><span>ex ample </span> </span>";
var trim_start = /^((<[^>]*>)*)\s+/;
while(text.match(trim_start)) {
text = text.replace(trim_start, "$1");
}
var trim_end = /\s+((<[^>]*>)*)$/;
while (text.match(trim_end)) {
text = text.replace(trim_end, "$1");
}
console.log(text);
The output is as expected - the only space is between ex ample
But this has a big problem if the replace might not change anything. Simply changing \s+ to \s* makes it turn into an infinite cycle. So, all in all, it works for my case but is not robust and to use it, you must be completely sure every single replace will change something when the regex matches.

comparing and replacing using regex in javascript : leaving a word in between

I am trying to replace a pattern as below:
Original :
welocme
Need to be replaced as :
welcome
Tried the below approach:
String text = "welocme";
Pattern linkPattern = Pattern.compile("a href=\"#");
text = linkPattern.matcher(text).replaceAll("a href=\"javascript:call()\"");
But not able to add the idvalue in between. Kindly help me out.
Thanks in advance.
how about a simple
text.replaceAll("#idvalue","javascript:call('idvalue')")
for this case only. If you are looking to do something more comprehensive, then as suggested in the other answer, an XML parser would be ideal.
Try getting the part that might change and you want to keep as a group, e.g. like this:
text = text.replaceAll( "href=\"#(.*?)\"", "href=\"javascript:call('$1')" );
This basically matches and replaces href="whatever" with whatever being caught by capturing group 1 and reinserted in the replacement string by using $1 as a reference to the content of group 1.
Note that applying regex to HTML and Javascript might be tricky (single or double quotes allowed, comments, nested elements etc.) so it might be better to use a html parser instead.
Add a capture group to the matcher regex and then reference the group in the replacemet. I found using the JavaDoc for Matcher, that you need to use '$' instead of '\' to access the capture group in the replacement.
Code:
String text = "welcome";
System.out.println("input: " + text);
Pattern linkPattern = Pattern.compile("a href=\"#([^\"]+)\"");
text = linkPattern.matcher(text).replaceAll("a href=\"javascript:call('$1')\"");
System.out.println("output: " +text);
Result:
input: welcome
output: welcome

Returning a String with whitespaces

I am using the below string and I want to return the substring with the blankspaces in javascript.
How can I do this?
As of now I used the normal substring function but its giving me the result after removing the blankspaces.
var Sting="CREC 20140615001CREC_GLOSS 18_0000033122 GLO4265 SGLB201406152014090120140531 TESTFOREF 0000000000033122 8-1 EQTY GB 21419 ACTUALS EUR000000000462098830 8738 N C70390000501F SQTY BUY 212102 49500.00# 9.34 8738 8738 "
var x= Sting.substring(1,27)
Result x= CREC 20
I don't want it like this, rather, I want my result to be
x= CREC 20
This is a browser thing - consecutive spaces are displayed as one. You might want to replace ' ' with and then it will display all spaces indiviudaly
x.replace(" ", " ");
Another way is to avoid displaying the string as HTML. For example the alert() function will show the correct number of spaces without the need to replace. Also displaying the string within a <pre> tag should work fine too.
I think Dobromir's interpretation of the OP is probably correct, and therefore a good answer.
If it is indeed a browser thing, then perhaps a better way to get it to display properly without changing the string itself is to style the HTML element with
white-space: pre
This will preserve the spaces like it does in a <pre> block.
See http://www.w3schools.com/cssref/pr_text_white-space.asp
If your spaces are always the same length you could do:
x.replace(" ", " ");
otherwise you can use a regular expression to replace multiple spaces with one:
x.replace(/\s+/g, ' ');
as seen Here

Javascript Regex Replace HTML Tags

Having a lot of difficulties using regex.
Heres what i am trying to do...
text<div> text </div><div> text </div><div> text </div>
to turn it in to
text<br> text<br>text<br>text
I've tryed doing...
newhtml = newhtml.replace(/\<div>/g,'<br>');
newhtml = newhtml.replace(/\</div>/g,' ');
but this gives the wrong output. Does jquery provide a better way of doing this?
That's because you're escaping the wrong thing, as only the backslash needs to be escaped.
newhtml = newhtml.replace(/<div>/g,'<br>');
newhtml = newhtml.replace(/<\/div>/g,' ');
Yes you are correct, jQuery does provide a better way of doing this.
An interesting read
first.
Easy, elegant, solution to your specific problem.
$('div').replaceWith(function(){
return "<br>"+$(this).html();
});​
jsFiddle
Don't use regexes if you don't need them; just replace string literals.
text.replace("<div>","<br>").replace("</div>","");
Note: This solution applies exactly to this scenario, I don't normally have anything against using regular expresions.
This must do the job:
text.replace(/(<\/?\w+?>)\s*?(<\/?\w+?>)|(<\/?\w+?>)/g,'<br>')
Though this will only work if there were no tags with some attributes like <div id="foo1">
You do not need to escape < as you did in your example, but instead you do need to escape /
A simple way to do this is the following:
$('.container').html(function(i, html) {
return html.replace(/<(|\/)div>/g, function(match) {
return match == '<div>' ? '<br>' : '';
});
});
/<(|\/)div>/: Matches <div> or </div>.
demo
Note: .container is where your html is placed.
One Liner using JQuery
newhtml = $(newhtml ).text().split(' ').join('<br/>');
You can achieve this using a simple RegExp
output = inputText.replace(/<\w{0,}\W{0,}>|<\W{0,}\w{1,}>/ig, "With whatever you want it to be replaced with")
Or you can do this
String.prototype.replaceTags = function( replacementText )
{
var x = new RegExp( "(" + replacementText + ")+" , "ig");
return this
.replace( /<\w{0,}\W{0,}>|<\W{0,}\w{1,}>/ig, replacementText )
.replace( x, replacementText )
}
And then call it directly on the String as follows
"text<div> text </div><div> text </div><div> text </div>".replaceTags( "<br>" )
You'll get this -- "text<br> text <br> text <br> text <br>"
This will search for portions in the string which begin with the "<" contains some text in between "div/p/br" additionally if the tag is being ended by "/" and finally the ">" closing of the tag. The ignore case will help when you are not sure that the element is written in Upper or Lower case.

Categories