Javascript: help with replacing '<div>' with '<br>' of an innerHTML! - javascript

I have an editable div where the user writes. As he writes, a javascript function adds the div html to a textarea. When the user presses SHIFT+Enter, the div gets a <br>. This is good.
But when the user presses Enter alone, the div gets <div></div> tags.
Therefore I try to make it so that when Enter is pressed, javascript scans the div's html to eliminate the </div> and change the <div> for <br>. The result will be that regardless of whether the user presses SHIF+Enter or Enter, the div's html will end up using only <br> for linebreaks.
<head>
<script type="text/javascript">
function doStuff(e){
if (window.event.keyCode == 13) {
var s=document.getElementById("divv").innerHTML;
s.replace("<div>", "<br>");
s.replace("</div>", "");
document.getElementById("divv").innerHTML=s;
}
document.getElementById("txtt").value = document.getElementById("divv").innerHTML;
}
</script>
</head>
<body>
<div contenteditable="true" id="divv" onKeyUp=doStuff(event);">
write here! Then press enter!
</div>
<textarea id="txtt" rows="30" cols="100">
</textarea>
</body>
My code doesn't work. When Enter is pressed, The textArea still shows div tags.
I'm not sure what I'm doing wrong. Please help.

The replace() method does not modify the string it's called on, it returns a new string with the occurrences replaced.
You can do something like:
var divv = document.getElementById("divv");
divv.innerHTML = divv.innerHTML.replace("<div>", "<br>").replace("</div>", "");

Usually browsers will have innerHTML store tags as <DIV> and </DIV> - you could try using:
s = s.replace(/<div>/ig,"<br>");
s = s.replace(/<\/div>/ig,"");

Firstly, if you use xhtml, you must use tag "< br / >".
Also draw attention on str.replace: it replaces only once.
js> var x = "hello";
js> x.replace("l", "L");
heLlo
Make your replace implementation:
js> function myreplace(str, pattern, change_to) {
var s = str;
var s2 = s;
do {
s2 = s;
s = s.replace(pattern, change_to);
} while (s2 != s);
return s;
}
js> myreplace("helllllo", "l", "L");
heLLLLLo

Related

txt.replace </blockquote> in textarea js

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.

Converting some text within an element to an element itself using JavaScript

Is this possible using JavaScript or JQuery, or anything else?
Say I have an HTML file like this
<div>
<p>Hello World</p>
</div>
And I want to turn "World" into a span element itself, like so (so that I can style just "World")
<div>
<p>Hello <span>World</span></p>
</div>
Since there are a lot of unknowns in your question, so I am assuming that you already know the string/word around which you want to add the html tag.
So keeping that in mind, following solution should work:
HTML:
<div>
<p id="my-text">Hello World, Again!</p>
</div>
JavaScript:
const stringToBeReplaced = "World"; // what you want to replace
const innerText = document.getElementById("my-text").innerText; //grab the text
const beginIndex = innerText.indexOf(stringToBeReplaced); // get text where string begins
// if string exists
if (beginIndex >= 0) {
const textWithTag =
"<span style='color: red'>" + stringToBeReplaced + "</span>";
const newString = innerText.replace(stringToBeReplaced, textWithTag);
// replace the text with new string
document.getElementById("my-text").innerHTML = newString;
}
Hope this is what you were asking and looking for.
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace3
str.replace solves the job. The comment of #Umer Hassan is correct.

comparing HTML text content with jQuery

I have a page where a specific div shows the ID for the user's "system role" like so:
<div id="systemRoleIndicator" style="display: none;">
<p>Z</p>
</div>
I can detect the value fine with jQuery, but I can't seem to actually use it for anything. For instance, I never receive the completion message in this code:
<script src="/scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var role = $("#systemRoleIndicator").text();
alert("Your role is: " + role); //displays proper value
if (role == "Z") {
alert("Code completed!");
}
</script>
Why might this be? Am I missing something about comparing strings?
Text for #systemRoleIndicator will also return leading and trailing space near p node. which returns text " Z " and not "Z".You need to either compare with the text of p element.:
var role = $("#systemRoleIndicator p").text();
or trim the text content of #systemRoleIndicator:
var role = $("#systemRoleIndicator").text().trim();

Get inner text and split it. Javascript problems using innerHTML and split

Having the next simple html code:
<div id="content">
This is a test
</div>
I don't understad why this is OK:
$(function(){
text = 'this is a text';
word = text.split(' ');
alert(word[1])
})
but this is not:
$(function(){
text = $('#content').text();
word = text.split(' ');
alert(word[1])
})
Jquery or native javascript, the problem is the same. I expect an alert with the same word in both cases, but only occurs in the first one. Where is my mistake?
Here is my problem:
http://jsfiddle.net/bbtdf/2/
Thanks!
Try this (You need to trim the text)
$(function(){
var text = $.trim($('#content').text()),
word = text.split(' ');
alert(word[1])
});
DEMO.
You need to trim the text/html because they will have spaces before and after the content
$(function(){
var text = $('#content').text(),
word = $.trim(text).split(' ');
console.log(word[1])
})
Demo: Fiddle
Else you need to write your html as <div id="content">This is a test</div>
Try with this code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<div id="content">
This is a test
</div>
<script>
$(function(){
text = $('#content').text();
word = text.split(' ');
alert(word[1])
});
</script>
You have 3 spaces for indentation in the content. The text function is returning the second space in the alert for this case, so it is seen blank.
Remove the indentation/spaces before the content, you should see the expected result.

Replace the contents of a div with regex match of string

I'm trying to figure out how to replace the contents of a <div> with the results from a regex .match() statement on a string. This is the code I have so far but I can't get it to work. I want the button to stay on screen but the <div> to reflect the matched word.
<html>
<body>
<script type="text/javascript">
function search(){
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.write(str.replace(document.getElementById("results"),
(str.match(patt1))));
}
</script>
</body>
<div id="results">So this is some text.</div>
<button name="Search" onclick="search()">Click Here</button>
</html>
Any ideas as to why it's not working?
You need to stop the button completing it's default event, which is to submit the page. (Edit: No it's not, its default event is nothing - assumed it was a <submit> :) )
In addition, to get a div from the document basic on it's id attribute, you use document.getElementById('id-of-element') and to set the contents of a div, you use .innerHTML on the element we just got.
// We need to take the event handler as a parameter for the function, let's call it e
function search(e){
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.getElementById("results").innerHTML = str.match(patt1)[0];
// This line stops the default action occurring
e.preventDefault();
}
Note: we don't need to specify an argument here, e goes in automatically
<button name="Search" onclick="search()">Click Here</button>
Your code is searching for the String "So this is come text." in the String "Visit W3Schools" and replacing it with the array ["W3Schools"], then writing it to the screen. This doesn't make much sense.
Try something like this instead:
function search(){
var str = "Visit W3Schools";
var patt1=/w3schools/i;
document.getElementById("results").innerHTML=(str.match(patt1))[0];
}
document.write will replace the entire page with the passed in parameter. So you just want to update that single DIV, results. So you want to use innerHTML:
function search() {
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.getElementById("results").innerHTML = str.match(patt1)[0];
}

Categories

Resources