new line for title JavaScript - javascript

I'm trying to put every new word for title on the new line using js. I tried different ways, but they don't work.
dictionary.title += word.value; - here I add attribute title for my dictionary class with word.value value. It comes together like: "HelloI'mJohn" instead of
"Hello
I'm
John". How can I do that on the new line using JavaScript code?

Use
\n
or
br tag
for new line.
dictionary.title += word.value + "\n";

Like in the above answers as said you can use <br> and \n for the new line but there are many alternative ways you can achieve this for your understand I have written a code where I used a tag which is also called a block element where it takes given width and height and add a new line at the end automatically. There are many block-level elements you can also use for new lines.
let value = document.querySelector(".newInput");
let btn = document.querySelector("button");
let div = document.querySelector(".dictionary");
function storeValues(){
let dictionary = "";
if(value.value){
dictionary += `<p>${value.value}</p>`
}
div.innerHTML += dictionary
}
btn.addEventListener("click", storeValues);
Enter Word: <input type='text' class='newInput'/>
<button type='submit' class='newInput'>Submit</button>
<div class='dictionary'>
<!-- Dicitonary will appear here-->
</div>

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.

How can I get the value of the first and second line in a textarea?

I'm trying to get the value of the first and second line from a textarea in HTML.
The main problem is that the first and second line can be of different lengths, so I can't just copy X amount of characters.
Most of the solutions I've seen include JQuery, which I'm not familiar with, so I would prefer an answer that doesn't involve JQuery. However, if you do have an answer that does use JQuery, I'll also give it a go.
Here's my code so far:
textarea {
resize: none;
}
<textarea id="c" placeholder="c" spellcheck="false"></textarea>
function getfirstAndsecondLine(inp) {
var splittedInput = document.getElementById(inp).value.split('\n');
var firstLine = splittedInput[0];
var secondLine = splittedInput[1];
console.log('first Line :' + firstLine);
console.log(" ");
console.log('second Line :' + secondLine);
}
<textarea id="c" placeholder="c" spellcheck="false"></textarea>
<button onclick=getfirstAndsecondLine('c')>
get first and second line
</button>
Assuming that the first and second line are separated by a newline (by pressing enter), you split it by "\n" then get the second element.
function getSecondLine() {
var tarea = document.getElementById("c")
var tareavalue = tarea.value;
var secondLine = tareavalue.split("\n")[1];
console.log(secondLine)
}

Remove HTML tags and formatting text

I would like to remove HTML tags between text and change newline to space. I'm using this pattern below but it is not perfectly. It adds two or more space between text. How to fix this pattern?
replace(/( |<([^>]+)>)/ig, ' ');
try below code and check
replace(/(<([^>]+)>)/ig,"");
UPDATE
You can do this way,
var html = 'Example: <h1></h1><p></p><div> </div><div>CONTENT</div> ';
html = html.replace(/\s|\n| /g, ' ');
html = html.replace(/<[^>]+>/gm, '');
Output will be like this,
Example: CONTENT
Play around the above solution & you will succeed.
Here is how I'll do what you want:
(See comments in my snippet)
// Input data
var input_data = `My<div><br>
<span></span>
<span></span>
</div><p>Content</p>`;
console.log("Input:", input_data);
// Creates html element with Input data
var elm = document.createElement('div');
elm.innerHTML = input_data;
// Use native function '.innerText' to get rid of the html,
// then replace new lines by spaces, and multiple spaces by only one space
output_data = elm.innerText.replace(/\n/g, ' ').replace(/[\s]+/g, ' ');
console.log("Output:", output_data);
Hope it helps!

Converting HTML to JavaScript string in PhpStorm

I'd like to convert some html easily into concatenated JS strings in PhpStorm.
From:
<div class="spa-shell-head">
<div class="spa-shell-head-logo"></div>
<div class="spa-shell-head-acct"></div>
<div class="spa-shell-head-search"></div>
</div>
To:
var main_html = ''
+ '<div class="spa-shell-head">'
+ ' <div class="spa-shell-head-logo"></div>'
+ ' <div class="spa-shell-head-acct"></div>'
+ ' <div class="spa-shell-head-search"></div>'
+ '</div>';
Ideally into the other direction as well. Is there any chance to achieve this? With a plugin? I could imagine that a macro with some regex could do it. Is it possbile?
Same question for other IDE can be found here. Or here.
Using only PHPStorm, you can use the Extra Actions plugin:
Select all your lines
Split the selection into lines (ctrl + shift + L)
Go to the beginning of the line (home)
Add a plus sign and a quote
Go to the end of the line (end)
Add a quote
Rather than converting HTML to a JS string, you should really create your elements in JS and then insert them into the DOM. This would give you much more control, not create such a difficult to maintain/read code, cause less problems, and be much faster to boot:
var outerDiv = document.createElement("div"); // Create a div
outerDiv.className = "spa-shell-head"; // Give it a class
var innerDivLogo = document.createElement("div");
innerDivLogo.className = "spa-shell-head-logo";
var innerDivAcct = document.createElement("div");
innerDivAcct.className = "spa-shell-head-acct";
var innerDivSearch = document.createElement("div");
innerDivSearch.className = "spa-shell-head-search";
outerDiv.appendChild(innerDivLogo); // Append into original div
outerDiv.appendChild(innerDivAcct);
outerDiv.appendChild(innerDivSearch);
document.body.appendChild(outerDiv); // Add to page
The above creates the following:
https://jsfiddle.net/yfeLbhe4/

Using javascript to alter span text dynamically and keeping the original text

I have a html page, inside which i have following code snippet, depending on which case we're following:
CASE 1) <p> <span id ="xyz"> some code here </span> </p>
CASE 2) <p> <span id ="xyz"> </span> some code here </p>
Now in my javascript code I have to write values in span xyz dynamically. If I try to do get reference to span xyz by id and then try to alter its innerHTML, then the html already present in span xyz is lost.
If I keep extra code outside the span, it appears on new line due to some css effects. I cannot alter css due to some reasons.
You can just store the current value in a String, and then modify this string:
var mySpan = document.getElementById('xyz').innerHTML;
mySpan += ' and this gets added after the some code here';
document.getElementById('xyz').innerHTML = mySpan;
or faster and more shorthand,
document.getElementById('xyz').innerHTML = document.getElementById('xyz').innerHTML + ' new text after'; //to add text after the existing text
document.getElementById('xyz').innerHTML = 'your new text before ' + document.getElementById('xyz').innerHTML; //to add text before.
You can append a new text node to span, if you want to keep the old text.
var newtext = document.createTextNode(" new text ");
var spanXyz = document.getElementById("xyz");
spanXyz.appendChild(newtext);
Refer these: createTextNode, appendChild
Edit: To add new text at the beginning, you can use something like
spanXyz.textContent = "new text " + spanXyz.textContent;
If you are not using jquery :
document.getElementById('xyz').innerHTML= document.getElementById('xyz').innerHTML + "XYZ";
If you are using jquery:
$("#xyz").append("xyz");
document.getElementById('xyz').innerHTML = 'some code here' + 'dynamically code';
or
document.getElementById('xyz').innerHTML = 'dynamically code' + 'some code here' ;

Categories

Resources