jQuery javascript regex Replace
with n – Even if we have a good project plan and a logical concept, we will spend the majority of our time correcting errors abaout javascript and jquery. Furthermore, our application can run without obvious errors with JavaScript, we must use various ways to ensure that everything is operating properly. In general, there are two types of errors that you’ll encounter while doing something wrong in code: Syntax Errors and Logic Errors. To make bug fixing easier, every JavaScript error is captured with a full stack trace and the specific line of source code marked. To assist you in resolving the JavaScript error, look at the discuss below to fix problem about jQuery javascript regex Replace
with n.
Problem :
How do i write a regex to replace <br />
or <br>
with n
. I’m trying to move text from div to textarea, but don’t want <br>
‘s to show in the textarea, so i want to replace then with n
.
Solution :
var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/<brs*[/]?>/gi, "n");
or using jQuery:
var str = $("#mydiv").html();
var regex = /<brs*[/]?>/gi;
$("#mydiv").html(str.replace(regex, "n"));
edit: added i
flag
edit2: you can use /<br[^>]*>/gi
which will match anything between the br
and slash
if you have for example <br class="clear" />
myString.replace(/<br ?/?>/g, "n")
True jQuery way if you want to change directly the DOM without messing with inner HTML:
$(‘#text’).find(‘br’).prepend(document.createTextNode(‘n’)).remove();
Prepend inserts inside the element, before() is the method we need here:
$('#text').find('br').before(document.createTextNode('n')).remove();
Code will find any <br> elements, insert raw text with new line character and then remove the <br> elements.
This should be faster if you work with long texts since there are no string operations here.
To display the new lines:
$('#text').css('white-space', 'pre-line');
a cheap and nasty would be:
jQuery("#myDiv").html().replace("<br>", "n").replace("<br />", "n")
EDIT
jQuery("#myTextArea").val(
jQuery("#myDiv").html()
.replace(/<br>/g, "n")
.replace(/<br />/g, "n")
);
Also created a jsfiddle if needed: http://jsfiddle.net/2D3xx/
Not really anything to do with jQuery, but if you want to trim a pattern from a string, then use a regular expression:
<textarea id="ta0"></textarea>
<button onclick="
var ta = document.getElementById('ta0');
var text = 'some<br>text<br />to<br/>replace';
var re = /<br */?>/gi;
ta.value = text.replace(re, 'n');
">Add stuff to text area</button>