Javascript / Jquery. Substitute plain text with html using regular expression with wildcard - javascript

I want to replace the plain text (for example) [next 1272] with
<a href='page.asp?id=1272'>
<img src='next.png' alt='Next Page' title='Next Page' />
</a>
The text could appear anywhere in the page html, and more than once, perhaps with a different number (from 1 to 99999). I don't have control of how/where it might appear.
Along the lines of
var ThisBody = $("body").html()
var regex = new RegExp("\\[ (I dont know) \\]", "g");
StrToReplaceWith = "...(the html in the example, with correct number)..."
ThisBody = ThisBody.replace(regex,StrToReplaceWith);
$("body").html(ThisBody);

Well I thought about it, and the following works, in case it's any help to anybody.
Not very elegant though
regex = new RegExp(/\[next (.*?)\]/gi);
mtch=ThisBody.match(regex)
newBody=ThisBody
if (mtch!=null)
{
if (mtch.length>0)
{
for (var i=0; i<mtch.length; i++)
{
tmp=mtch[i] // [next 1272]
tmp=tmp.replace("]","") // [next 1272
tmp=tmp.substring(6) // 1272
t="<a href='page.asp?id=" + tmp + "'>"
t+="<img src='Next.png' alt='Next Page' title='Next Page' />"
t+="</a>"
newBody=newBody.replace(mtch[i],t)
}
}
}
ThisBody=newBody

Related

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/

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.

Match a String in a Webpage along with HTML tags

With below code, I am trying to match a text in a web page to get rid of html tags in a page.
var body = $(body);
var str = "Search me in a Web page";
body.find('*').filter(function()
{
$(this).text().indexOf(str) > -1;
}).addClass('FoundIn');
$('.FoundIn').text() = $('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>");
But it does not seems to work.. Please have a look at this and let me know where the problem is...
here is the fiddle
I have tried the below code instead..
function searchText()
{
var rep = body.text();
alert(rep);
var temp = "<font style='color:blue; background-color:yellow;'>";
temp = temp + str;
temp = temp + "</font>";
var rep1 = rep.replace(str,temp);
body.html(rep1);
}
But that is totally removing html tags from body...
change last line of your code to below one...you are using assignment operator which works with variables not with jquery object ..So you need to pass the replaced html to text method.
$('.FoundIn').text($('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>"))
try this.
$('*:contains("Search me in a Web page")').text("<span class='redT'>Search me in a Web page</span>");

How to include javascript generated text into html link?

I have a javascript that displays a generated text into a div:
document.getElementById('phrase').innerHTML = phrase;
PHRASE_TEXT_GETS_SHOWN_HERE
Basically I'm trying to set up a link that will take the text and post it to twitter with a link:
Clicky for tweety
How can I include the generated text in the link?
Do you mean like:
function setPhrase(phrase) {
var url = 'http://twitter.com/home?status=' + encode(phrase);
$('#phrase').html('' + phrase + '');
}
...?
Un-jQuerying it should be straightforward enough, if that's how you roll.
This is un-jQueried:
function setPhrase(phrase) {
var url = 'http://twitter.com/home?status=' + encodeURI(phrase);
document.getElementById('phrase').innerHTML = '' + phrase + '';
}
If you didn't see my failbraining encode for encodeURI as an error you should use Firebug. It may also fail if you have more than one element with the id phrase or if you have no elements with the id phrase.

Categories

Resources