jQuery javascript regex Replace <br> with \n - javascript

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.

var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/<br\s*[\/]?>/gi, "\n");
or using jQuery:
var str = $("#mydiv").html();
var regex = /<br\s*[\/]?>/gi;
$("#mydiv").html(str.replace(regex, "\n"));
example
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>

Related

Contenteditable regex whitespace not working

I am trying to validate if the contenteditiable value has only whitespace/blank space. In my example if the value have only whitespace/blank space it should not match according to my regex string, but it not working as intended. It keeps matching when I enter complete blank spaces.
edit: the black space is where you can enter text.
https://jsfiddle.net/j1kcer26/5/
JS
var checkTitle = function() {
var titleinput = document.getElementById("artwork-title").innerHTML;
var titleRegexp = new RegExp("^(?!\s*$).+"); //no blank spaces allowed
if (!titleRegexp.test(titleinput)) {
$('.start').removeClass('active-upload-btn');
console.log('no match')
} else if (titleRegexp.test(titleinput)) {
$('.start').addClass('active-upload-btn');
console.log('match')
}
};
$('#artwork-title').on('keyup change input', function() {
checkTitle();
});
HTML
<div class="post-title-header">
<span class="user-title-input title-contenteditable maxlength-contenteditable" placeholder="enter text here" contenteditable="true" name="artwork-title" id="artwork-title" autocomplete="off" type="text" spellcheck="false">
</span>
</div>
<div class="start">
turn red if match
</div>
If you look at the actual inner HTML, you'll see things like <br> elements or entities. Your regex doesn't look equipped to handle these.
You may want to consider using textContent instead of innerHTML if you just care about the text, not the HTML. Or alternatively, if you really want plain text, use a <textarea/> instead of a content-editable div, which is for rich-text-style editing that produces HTML.
Edit:
Your regex is not quite right either. Because you're using the RegExp constructor with new RegExp("^(?!\s*$).+"), the \s in your string literal is going to turn into a plain s; you have to use a \\s if you want the regex to have an actual \s in it. IMO, it's always better to use a regexp literal unless you're building one dynamically, like /^(?!\s*$).+/, or I find this to be a simpler alternative to tell you if a string is entirely whitespace: /^\s+$/.

Get text inside an HTML element, store it in a variable and add class to all the other matches in the DOM

I am trying to achieve this:
I have this code:
<h1>Search results for "<span>photoshop</span>"</h1>
And, I have another code like this in the same page:
<p>Photoshop is the best photo editor in the world</p>
With jQuery or pure JavaScript, I want to get the word within the span which changes dynamically, store it in a variable, and wrap every other 'photoshop' word in the document with a 'highlighted' class. How can I do this?
You can use a regular expression and jQuery's html() function to find and replace all occurances of a word with that word wrapped in a span.
<h1>Search results for "<span id="search">Photoshop</span>"</h1>
var theWord = $('#search').text(),
patt=new RegExp('\\b(' + theWord + ')\\b', 'gi');
$('body').html($('body').html().replace(patt,'<span class="highlight">$1</span>'));
(use 'gi', if you want it to be global and case insensitive)
http://jsfiddle.net/EBWQX/2/
and if you can't give the span an id, maybe selecting $('h1 span') would be specific enough (depending on your code)
You can try to use jQuery Highlight Plugin.
Example there:
HTML:
<input onkeyup="setNewSearch(this);" />
<h1>Search results for "<span id="search"></span>"</h1>
<!-- text -->
Javascript:
function setNewSearch(input){
var value = $(input).val();
$("#search").html(value);
$("body").unhighlight();
$("body").highlight(value);
}

How do I display new line in .text() in jQuery?

I have the following code:
var stringDisplay = "Hello\nWorld";
$("#meaning").text(stringDisplay);
It is displaying \n instead of a newline.
The output is showing up as Hello\nWorld.
I used <br> tag also in place of \n, but it's still not working.
You will have to use both .html() and replace the newline:
var escaped = $('<div>').text(stringDisplay).text();
$('#meaning').html(escaped.replace(/\n/g, '<br />'));
An alternative would be to style the element:
white-space: pre-wrap;
How about this
$('meaning').html('line1<br>line2');

Getting non-html text from CKeditor

In my application, in insert news section, i use a sub string of news content for news Summary. for getting news content text from users,i use CKEditor and for news summary i use substring method to get a certain length of news content.but when i'm working with CKEditor i get text with html tags and not plain text and when i use substring method, my news summary become messed! how do i get raw text from this control?
i read this but i can't use getText() method
Try code like this:
CKEDITOR.instances.editor1.document.getBody().getText();
It works fine for me. You can test it on http://ckeditor.com/demo. It's not ideal (text in table cells is joined together without spaces), but may be enough for your needs.
EDIT (20 Dec 2017): The CKEditor 4 demo was moved to https://ckeditor.com/ckeditor-4/ and uses different editor names, so the new code to execute is:
CKEDITOR.instances.ckdemo.document.getBody().getText();
It's also important that it will work in the "Article editor" and in the "Inline editor" you need to get text of a different element:
CKEDITOR.instances.editor1.editable().getText();
do it like this
//getSnapshot() retrieves the "raw" HTML, without tabs, linebreaks etc
var html=CKEDITOR.instances.YOUR_TEXTAREA_ID.getSnapshot();
var dom=document.createElement("DIV");
dom.innerHTML=html;
var plain_text=(dom.textContent || dom.innerText);
alert(plain_text);
viola, grab the portion of plain_text you want.
UPDATE / EXAMPLE
add this javascript
<script type="text/javascript">
function createTextSnippet() {
//example as before, replace YOUR_TEXTAREA_ID
var html=CKEDITOR.instances.YOUR_TEXTAREA_ID.getSnapshot();
var dom=document.createElement("DIV");
dom.innerHTML=html;
var plain_text=(dom.textContent || dom.innerText);
//create and set a 128 char snippet to the hidden form field
var snippet=plain_text.substr(0,127);
document.getElementById("hidden_snippet").value=snippet;
//return true, ok to submit the form
return true;
}
</script>
in your HTML, add createTextSnippet as onsubmit-handler to the form, eg
<form action="xxx" method="xxx" onsubmit="createTextSnippet();" />
inside the form, between <form> and </form> insert
<input type="hidden" name="hidden_snippet" id="hidden_snippet" value="" />
When the form is submitted, you can serverside access hidden_snippet along with the rest of the fields in the form.
i personally use this method to compact the code and remove also double spaces and line feeds:
var TextGrab = CKEDITOR.instances['editor1'].getData();
TextGrab = $(TextGrab).text(); // html to text
TextGrab = TextGrab.replace(/\r?\n|\r/gm," "); // remove line breaks
TextGrab = TextGrab.replace(/\s\s+/g, " ").trim(); // remove double spaces
I used this function:
function getPlainText( strSrc ) {
var resultStr = "";
// Ignore the <p> tag if it is in very start of the text
if(strSrc.indexOf('<p>') == 0)
resultStr = strSrc.substring(3);
else
resultStr = strSrc;
// Replace <p> with two newlines
resultStr = resultStr.replace(/<p>/gi, "\r\n\r\n");
// Replace <br /> with one newline
resultStr = resultStr.replace(/<br \/>/gi, "\r\n");
resultStr = resultStr.replace(/<br>/gi, "\r\n");
//-+-+-+-+-+-+-+-+-+-+-+
// Strip off other HTML tags.
//-+-+-+-+-+-+-+-+-+-+-+
return resultStr.replace( /<[^<|>]+?>/gi,'' );
}
Function call:
var plain_text = getPlainText(FCKeditorAPI.GetInstance("FCKeditor1").GetXHTML());
I created this fiddle for testing: http://jsfiddle.net/4etVv/3/
I use this method (need jQuery):
var objEditor =CKEDITOR.instances["textarea_id"];
var msg = objEditor.getData();
var txt = jQuery(msg).text().replaceAll("\n\n","\n");
hope it helps!
Assuming that editor is your CKEditor instance (CKEditor.instances.editor1 from above example or if you are using events then event.editor). You can use following code to get plain text content.
editor.ui.contentsElement.getChild(0).getText()
Apparently CKEditor adds a "voice label" element to the actual editable content. Hence getChild(0).

How to delete string from string with regex and jQuery/JS?

I wonder, how to delete:
<span>blablabla</span>
from:
<p>Text wanted <span>blablabla</span></p>
I'm getting the text from p using:
var text = $('p').text();
And for some reason I'd like to remove from var text the span and its content.
How can I do it?
It's impossible to remove the <span> from the variable text, because it doesn't exist there — text is just text, without any trace of elements.
You have to remove the span earlier, while there is still some structure:
$('p').find('span').remove();
Or serialize the element using HTML (.html()) rather than plain text.
Don't edit HTML using regular expressions — HTML is not a regular language and regular expressions will fail in non-trivial cases.
var html = $('p').html();
var tmp = $('<p>').html(html);
tmp.find('span').remove();
var text = tmp.text();
text = text.replace(/<span>.*<\/span>/g, '');
to remove the unwanted whitespace before the <span> use
text = text.replace(/\s*<span>.*<\/span>/g, '');
leaving you with
<p>Text wanted</p>

Categories