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

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.

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.

Regex in combination with jQuery text() method

$(document).ready(function(){
var regex1 = $('#element').text().match(/\b(06\d{8})\b/g);
console.log('regex1: ' + regex1);
var regex2 = $('#element').text().match(/(06\d{8})/g);
console.log('regex2: ' + regex2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "element">
0600000000
0600000001
<div>0600000002</div> 0600000003
TEST:0600000004
<span>0600000005</span><span>TEST0600000006</span><span>0600</span><span>000007</span>
</div>
What is want is only 6 matches 0600000000-0600000005.
Looks great when I use this regex: /\b(06\d{8})\b/g https://regex101.com/r/fE6gJ7/1
But.., when I use the jQuery text() it looks like the output of text() replaces every HTML tag with "nothing":
Output $(element).text()
0600000000
0600000001
0600000002 0600000003
TEST:0600000004
0600000005TEST06000000060600000007
Is it possible to avoid this? Or can I replace every HTML tag with a single space?
Or what is the alternative(iterate over all text elements?)
Use .html() insetad of .text(). .text() will remove the HTML tags inside the element and the textContent will be concatenated with other text.
So, using text() on the parent element for following
<span>0600000005</span><span>TEST0600000006</span><span>0600</span><span>000007</span>
will give
0600000005TEST06000000060600000007
And regex will not capture anything here because of word boundary.
Demo:
$(document).ready(function(){
var regex1 = $('#element').html().match(/\b(06\d{8})\b/g);
console.log('regex1: ' + regex1);
var regex2 = $('#element').html().match(/(06\d{8})/g);
console.log('regex2: ' + regex2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "element">
0600000000
0600000001
<div>0600000002</div> 0600000003
TEST:0600000004
<span>0600000005</span><span>TEST0600000006</span><span>0600</span><span>000007</span>
</div>

remove html tags from string js/jquery

I'm trying to show a text that i'm getting from the server with html tags.
Let's say i got
"a\nb\nc\nd\ne\nf\n"
and i want to show
a
b
c
d
e
f
i tried using jquery text() but i get empty string:
var answer = params.question.answer;
$('#answer_text').html($(answer).text());
i also tried with regex but nothing happens:
var regex = /(<([^>]+)>)/ig;
var answer = params.question.answer.replace(regex, '');
$('#answer_text').html(answer);
You need to convert \n into <br/> for creating line breaks in html:
var answer= "a\nb\nc\nd\ne\nf\n";
$('#answer_text').html(answer.replace(/\n/g, "<br />"));
Working Demo
Using REGEX Remove \n and add <br /> tag.
Try:
var answer = "a\nb\nc\nd\ne\nf\n";
var regex = /\n/gi;
$('#answer_text').html(answer.replace(regex, "<br />"));
Demo
Another option is to use the white-space rule
var answer = "a\nb\nc\nd\ne\nf\n";
$('#answer_text').html(answer);
#answer_text {
white-space: pre-line;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="answer_text"></div>

Javascript replace every line of value

So I have this script which has to find some text on the first textarea (right away when text is pasted), then replace it with another one and give the result to another textarea.
The problem is that it's replacing the text only for the first line. And I want it to replace it on the All lines.
My code: (doesn't work on JSfiddle, but do on HTML)
<script>
function go()
{
var str = document.getElementById("a").value;
resa=str.replace("http://","www.");
resb=resa.replace(".com","");
document.getElementById("b").value=resb;
}
</script>
<textarea rows="10" cols="140" onkeyup="go()" id="a">
</textarea>
<textarea rows="10" cols="140" onkeyup="go()" onclick="this.focus();this.select();" id="b">
</textarea>
So if you try to enter https://google.com in every line you will get right text on the other textarea, but only in the first line.
You need to do a global replace.
var str = document.getElementById("a").value;
var resa=str.replace(/http\:\/\//g,"www.");
var resb=resa.replace(/\.com/g,"");
It's not that only the first line is replaced. The problem is you're only replacing the first occurrence.
Change to use a regex to replace all:
var resa = str.replace(new RegExp('http://', 'g'), 'www.');
var resb = resa.replace(new RegExp('.com', 'g'), '');
document.getElementById("b").value = resb;

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

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

Categories

Resources