Converting HTML to JavaScript string in PhpStorm - javascript

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/

Related

new line for title 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>

Need help to add javascript array contents to an existing piece of HTML code

My front-end skills are fairly limited. I have a trained language model which generates 'tweets'.
I have this javascript function which currently displays the tweets as a paragraph.
function addResponse(msg) {
document.getElementById("results").textContent = ""
var para = document.createElement("div");
var s = "<div class='center' id='gpt2'> <b> Here what our BOT has to say... </b> </br></br>"
i = 1
for (var key in msg){
var value = msg[key];
console.log(value);
s = s + i + ") " + " <b>" + value + "</b> </br></br>"
i = i + 1
}
para.innerHTML = s + "</div>";
document.getElementById('append').appendChild(para);
}
Instead of displaying in a paragraph, I want to display as a proper tweet.
Here is a tailwind CSS implementation to create the UI of the tweet: https://codepen.io/webcrunchblog/pen/xedQVv
Currently this displays a fixed string "Starhopper". What I want to do is, loop through my array object 'msg' and display all the tweets with the proper UI .
Currently the addResponse() is called as part of ajax callback for successful response. From there how can I include the tailwind CSS code so that I can display every array element in its own tweet UI?
Hope the question is clear.
EDIT: Created this codepen if anyone wants to try it out: https://codepen.io/nikhilno1/pen/RwPBWvb
In the output, there is a tweet and three sentences. I want 3 tweets to be created for each of the sentence.
I've updated a bit of your code here: https://codepen.io/rxna/pen/OJVwMOm
The idea is to:
Clone the tweet element, have added a custom class for that:
var articleNode = document.querySelector(".tweet-body");
var clone = articleNode.cloneNode(true);
Update the text within each element:
var title = clone.querySelector(".tweet-text");
title.innerText = value;
And lastly append within the DOM:
document.getElementById("append").appendChild(clone);
It's not perfect but hopefully you'd get the idea.

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!

How to hard code text which are coming from javascript messages

Our application is been internationalized and being changed to different languages. For that reason we have to hard code all the messages. How can we do that for messages in javascript ?
This is how we are doing in html messages.
<span th:text="#{listTable.deletedFromTable}">deleted</span>
How do we hard code for javascript messages.(update the table)
$('#TableUpdate-notification').html('<div class="alert"><p>Update the Table.</p></div>');
You will need to put the messages in the DOM from the start, but without displaying them. Put these texts in span tags each with a unique id and the th:text attribute -- you could add them at the end of your document:
<span id="alertUpdateTable" th:text="#{listTable.updateTable}"
style="display:none">Update the Table.</span>
This will ensure that your internationalisation module will do its magic also on this element, and the text will be translated, even though it is not displayed.
Then at the moment you want to use that alert, get that hidden text and inject it where you need it:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + $('#alertUpdateTable').html() + '</p></div>');
You asked for another variant of this, where you currently have:
$successSpan.html(tableItemCount + " item was deleted from the table.", 2000);
You would then add this content again as a non-displayed span with a placeholder for the count:
<span id="alertTableItemDeleted" th:text="#{listTable.itemDeleted}"
style="display:none">{1} item(s) were deleted from the table.</span>
You should make sure that your translations also use the placeholder.
Then use it as follows, replacing the placeholder at run-time:
$successSpan.html($('#alertTableItemDeleted').html().replace('{1}', tableItemCount));
You could make a function to deal with the replacement of such placeholders:
function getMsg(id) {
var txt = $('#' + id).html();
for (var i = 1; i < arguments.length; i++) {
txt = txt.replace('{' + i + '}', arguments[i]);
}
return txt;
}
And then the two examples would be written as follows:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + getMsg('alertUpdateTable') + '</p></div>');
$successSpan.html(getMsg('alertTableItemDeleted', tableItemCount));

Adding tags to HTML using javascript

I have HTML produced from XSLT that looks like:
<span id="text">It's like what Sir Ian McKellan told me the day I sold my boat to Karl Lagerfeld: <span id="quote">Parting is such sweet sorrow.</span></span>
I'm trying to use javascript to parse it such that extra tags are added to mark the context around the quote. The goal is to give users the option whether or not to display the quote plus context or just the quotation. The end result would be, e.g.,
<span id="text"><span id="preContext">It's like what Sir Ian McKellan told me the day I sold my boat to Karl Lagerfeld: </span><span id="quote">Parting is such sweet sorrow.</span></span>
This way, it would be simple to define the style.display of preContext as none. I've tried using insertAdjacentHTML; for example,
document.getElementById("text").insertAdjacentHTML('afterbegin', "<span id='preContext'>");
document.getElementById("quote").insertAdjacentHTML('beforebegin', "</span>");
But, as I've discovered, insertAdjacentHTML can insert nodes but not individual tags. The above gets me <span id="text"><span id="preContext"></span>It's like. . .
Is this possible in javascript, or does this need to be done in XSLT? (PS: I don't want to use JQuery. . )
Working example: http://jsfiddle.net/vcSFR/1/
This code gets the first textNode, wraps it in a span, and then swaps the original first text node for the new span.
var oDiv = document.getElementById("text");
var firstText = "";
for (var i = 0; i < oDiv.childNodes.length; i++) {
var curNode = oDiv.childNodes[i];
if (curNode.nodeName === "#text") {
firstText = curNode.nodeValue;
break;
}
}
firstTextWrapped = '<span id="preContext">' + firstText + '</span>';
oDiv.innerHTML = oDiv.innerHTML.replace(firstText, firstTextWrapped);
Thanks to https://stackoverflow.com/a/6520270/940252 for the code to get the first textNode.

Categories

Resources