Javascript multiline string replacement with multiline string - javascript

I was trying to replace multiline string with another multiline string using javascript.
How do I do that?
For example the pseudo code for this could be as shown below, where the string to search and set are runtime variables/arguments (not hardcoded as shown below), so we cannot create fixed regular expressions.
Any idea?
The string to search for looks like,
<tr>
<td colspan="3" class="footer"> </td>
</tr></tbody></table>
and let the string to replace be,
<tr>
<td colspan="3" class="footer">New Arrivals!!!</td>
</tr>
<tr>
<td colspan="3" class="footer"> </td>
</tr></tbody></table>
Pseudo code,
var regExp = new RegExp(strMultiLineTextToSearch.trim(), "gm");
var matches = htmlContent.match(regExp);
alert(matches.length);
if(matches.length > 0){
var newHtml= htmlContent.replace(regExp , strMultiLineTextToSet );
}
Using Firefox 22.0

also, the strings are prased from webpage using some string foo and innerHTML.
EEEK! Don't use HTML manipulation to add content to a table. That would be like adding a small detail to a big painting by having a painter describe the picture to you, then paint a new picture based on that description, except you change that little detail in the description.
Not just it's incredibly slow, but the painter is likely to not use the very same words you used when telling him to draw the picture the first time. You will be confused if he says "young woman" instead of "lady". You wanted the lady to hold something, but there's only a young woman. Instead, you should tell the painter to give the lady that something.
The same applies here: are you sure you use the exact same amount of whitespace in the string you're searching as is in the table? If there isn't, the string won't be found. Even if there is, how can you be sure the browser doesn't rearrange the attributes within a tag (IE loves to sort them alphabetically)? Add whitespace after the arguments? Some browser extension may add its own attributes or classes...
Instead, use DOM manipulation. That's the picture. HTML is its description.
If you add an ID to that row, it will be easy to find from javascript. Then create the new element and place it before that row.
var lastRow = document.getElementById("last-row")
var td = document.createElement("td")
td.className = "footer"
td.colspan = 3
var text = document.createTextNode("New arrivals!!!")
td.appendChild(text)
lastRow.parent.insertBefore(lastRow, td)
If the table is easy to find, you can access its last row via that table:
var table = document.getElementById("my-table")
var lastRow = table.rows[table.rows.length - 1]
...
It seems you are using the table to layout your page. This is not a clean approach (the page is not semantically a table, lots of unneccessary elements; please note the distinction between <table> and display:table). Adding an empty spacing cell is almost certainly wrong. Use CSS margin-bottom or padding-bottom instead (unless you're making an HTML email - in which case, use CSS anyways, then convert to a mail-safe form using some freeware web service that exists for that purpose). CSS is not hard. Not using it is much harder.

You can't have Strings spanning across multiple lines. If you want a String that contains newline characters you'll have to use escape sequences: \n. Also pay attention not to use double quotes in a string that is itself enclosed in double quotes - you need to escape those, too.
var foo = "I am a string that contains a \" double quote"
or
var foo = 'I am a string that contains a " double quote'
are legal while
var foo = "I am a string that contains a " double quote"
is not

The problem I see here is that you're using double quotes where they are not allowed and lack of \n in the end of each line in your strings:
var strMultiLineTextToSearch =
"<tr>
<td colspan="3" class="footer"> </td>
</tr></tbody></table>";
should be
var strMultiLineTextToSearch =
"<tr>
<td colspan='3' class='footer'> </td>
</tr></tbody></table>";

Related

Javascript get inner HTML text for span by class name

This is the basic format of the code the table is contained within a div named
<div class="leftCol">
.....
<tr id="my_cd">
<td><span class="agt_span">My Code</span></td>
</tr>
.....
</div>
I need to be able to get whatever text is contained within the span class, in this case I need to pull the text "My Code" and then add that into an array. Adding the text into an array is not the issue that's easy but I can't figure out how to pull the text. No matter what I try I can't get anything but an 'undefined' value.
How do I get the Inner HTML text value for a span by class name?
First Question solved thanks!!
Second question expand on first:
<div class="leftCol">
.....
<tr id="my_cd">
<td><span class="agt_span">My Code</span></td>
<td>
<div>
<select name="agt_drp" id="agt_drp" class="agt_drp">...</select>
</div>
</td>
</tr>
</div>
Let's say I have the select id "agt_drp" and I want to get the span class text. Is there any way to do that?
Jquery:
var test = $("span.agt_span").text();
alert(test):
Javascript:
http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
in vanilla javascript, you can use getElementsByClassName():
var htmlString = document.getElementsByClassName('agt_span')[0].innerHTML;
https://jsfiddle.net/ky38esoo/
Notice the index behind the method.
JQuery:
$('span.agt_span').text();
Pure JavaScript (you need to specify the position of your class element: [0] to get the first one):
document.getElementsByClassName('agt_span')[0].innerHTML;
If you have multiples elements with this class, you can loop on it:
var elts = document.getElementsByClassName('agt_span');
for (var i = 0; i < elts.length; ++i) {
alert(elts[i].innerHTML);
}
Though getElementsByClassName seems to be supported by all major browser, that is now argument to use it. To keep your code compatible and usefull, better use the W3C Standard DOM Level 3 Core. The Document IDL does not describe such a method there!
So please use
var table = document.getElementById("my_cd"); /* id is unique by definition! */
var spans = table.getElementsByTagName("span");
var txt;
for(i in spans) {
if(spans[i].getAttribute("class").contains("agt_span")){
txt = spans[i].firstChild; /* a span should have only one child node, that contains the text */
}
}
return txt;
This method isn't perfect, as you actually need to split the spans[i].getAttribute("class").split(" ") on space chars and check if this array contains "agt_span".
By the way: innerHTML is no DOM Attribute too. But you can implement anything in a compatible and flexible way using W3C DOM and you will be sure to write effective and compatible code.
If the js programmers had used the W3C Documents and if there weren't no Internet Explorer to break all those ECMAScript and W3C rules, there would never have been that many incompatibilities between all those browser versions.

jquery selector from html comment [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have little big problem. I try almost everything and I am not able to select an element from table if I know some commented text. I think that this is not possible. For example
<table id='table1'>
<tr>
<td>
Some text
</td>
<td>
<!-- someid="id301" -->
</td>
</tr>
<tr>
<td>
Some next text
</td>
<td>
<!-- someid="id303" -->
</td>
</tr>
<table>
OK. So I only know for example this value someid="301" or someid="302". And I need to get parent element for example to change color of this by jquery. I really tested everything and I am not able to get tr element. Thank you for your help.
You can filter out the content of each TDs but honestly i don't see any purpose for that:
var someValue = 'someid="id303"';
$('table').find('td').contents().filter(function(){
return this.nodeType === 8 && this.nodeValue.indexOf(someValue) != -1;
}).closest('tr').css('background-color', 'red');
-jsFiddle-
If you need that string to setup something, then generally it is not a good practice to put that string in comment.
I would suggest you to put that someid as a data attribute in td element
<td data-someid="id301">...</td>
then you can access it by $td.attr("data-someid") or even use it in jQuery selector
$('td[data-someid="id301"]').css('background-color', 'green');
You can use jQuery Comments() Plug-in or
<input type="hidden" id="id301">
Try this:
<script>
var tableId = 'table1';
var table = document.getElementById(tableId);
var trs = table.getElementsByTagName('tr');
// Pattern for searching for the string like someid="id[somenumbersinarow]"
var pattern = /someid=\"id[0-9]+\"/
// Pattern for searching for numeric value
var numericPattern = /[0-9]+/
var innerHTML, tr;
for (var i = 0, amountOfTrs = trs.length; i < amountOfTrs; i++){
tr = trs[i];
innerHTML = tr.innerHTML;
/* Searching for the comment with "someid" string, turning it into string
(it will be the only string because there will be a single element in the array),
then again search for numbers, convert to string and try to parse it) */
console.log(parseInt(innerHTML.match(pattern).toString().match(numericPattern)));
}
</script>
This script properly works if there's only one comment per the TR element
pattern is a regular expression object. It can be used with modifiers such as g (search for ALL the matches in the text), for instance: /[0-9]+/g. In this case you'll get an array which may have a length greater than 1.
In the example I provided the modifier isn't used, so toString() method will return a string in this case. If you go further and try to get a number by another pattern, then you can use parseInt to extract number (id)
Be aware that if the match() method doesn't find anything it returns null, so before invoking function like in my example, you should either strongly know that this comment exists or perform some additional check.

Javascript regular expression prevent matching inside tags

I have to match a string that is not inside tags. I am working on projects that I don't have control over the back-end html rendering code. What I need to do is add a hover functionality for multiple dynamic words. I created a script that will look for those key words in specific elements and add their description in title tags for the hover. My problem is that if other keywords are found in other keyword's title tags.
My JS:
var str = 'match <span title="not match here">match</span> match';
str.replace( /match/gim, 'ok' );
I do not want the "match" word in the title attribute to be replaced, my desired result is:
'ok <span title="not match here">ok</span> ok'
how can I do that with Javascript?
I tried the expression below but it's not working for me:
^((?!(".+")match)*$
You need to capture tags first to be able to avoid them:
var result = str.replace(/(<[^>]*>)|match/gi, function (_,g1) {
return (g1==undefined)? 'ok':g1;
});
But if you can, using the DOM is probably the best way.

Can I insert some string at every other line using javascript?

Let's say I have a large wall of text that I've pasted onto my page inside a div with id "story". Each paragraph is actually on a single line in the html file, and each paragraph is separated by a single line. I want to make the wall of text more readable using bootstrap. I've set the css in a blog like format, is there any way to dynamically add </p><p> at every paragraph separation?
var paragraphs = "your text".split(/\n\s*\n/);//since paragraphs are separated by
for(var i = 0; i < paragraphs.length; i++){ //a line, we need two \n here.
var p = document.createElement("p");
p.innerHTML = paragraphs[i].trim();
document.querySelector("#story").appendChild(p);
}
//==============
//To get the text of an element (with new lines), you can do this:
document.querySelector("#story").childNodes[0].wholeText;
Maybe something like this? http://jsfiddle.net/DerekL/qv2GZ/
What you shouldn't do is replacing text inside a string and dumping it right into DOM. That's bad practice. That's why here I'm creating a p element instead of replace lines with </p><p>.
I think that you should take a look here:
How do I replace all line breaks in a string with <br /> tags?
And here: How to replace all occurrences of a string in JavaScript?
Remember that new line is simply \n. Then it is a matter of simple string replace. There is a huge research about it, and the question is a possible duplicate, so I think that is enough to answer :).
Best regards!

How to parse formula of html table cell to acting like Excel, using Javascript

I am looking for a way to make html table acting like excel using Javascript (Jquery preferred). Here are my problem. I made a table like this:
<table>
<tr>
<td id="A1">10</td>
<td id="B1">10.5</td>
</tr>
<tr>
<td id="A2">5</td>
<td id="B2" formula="A1+B1+A2"></td>
</tr>
</table>
Every td has an id, some of those tds are added a formula attribute. And I wanna to calculate those formula, give the value of formula to the td.
In the table above, here, I wanna assign the B2 value 25.5(B2=A1+B1+A2).
Look like this:
<td id="B2" formula="A1+B1+A2">25.5</td>
Can anybody give me a clue? Thanks.
PS: Here are some resource that I found, but they do not solve my problem
Spreadsheet-like formulas on the DOM
http://zaach.github.com/jison/docs/
Thanks a lot #palindrom. I finally solved my problem based on your answer.
Here is my code:
$("td[formula]").each(function(){
//1 get formula attribute
var formula = $(this).attr('formula');
//2 use regex to make expression, with the surpport of "A122", "AB1" and more
var expression = formula.replace(/([A-Z]+[0-9]+)/g, "parseFloat(\$('#$1').html())") ;
//3 eval the expression
var result = eval( expression );
//4 set the value
$(this).html(result);
});
Should work for simple math, didnt try:
$("td[formula]").each( function() {
this.html( eval( this.attr("formula").replace(/[a-z][0-9]/g, "\$('#$0').html()") ) );
} );
Edit:
If you have functions like sum in the formulas, implement them as javascript functions and they should work too.
even if this too late, try this plugin https://github.com/xsanisty/jquery-calx
I have develop it using jison parser in its core, it will parse the formula in the data-formula attribute just like you want
This is a html table I wrote in which a formula is computed for each line (see iframe source).
The formula is written in JavaScript (as complex as can be) in which [abc] is replaced with the value of cell with id=abc (weights from the header) and {abc} with the text in cell from the same column in that line.
The columns are sortable
The weights are modifiable by the user and they are remembered in a cookie.
Hoping this can help.

Categories

Resources