0

I have a string that begins and ends with the table row tag <tr>...</tr>. There are multiple <td>s inside this, that take the form:

<td class="someClass">TextIWant TextI Do NOtWant</td><td><img src='green.png'></td>
<td class="someClass">TextIWant TextI Do NOtWant</td><td><img src='blue.png'></td>

What I'm looking to do, is look at the color.png, and add a class to the td, and trim some of the text inside the td. The final output should be something like:

<td class="someClass green">TextIWant</td>
<td class="someClass blue">TextIWant</td>

How can I do this with regular expressions?

8
  • 1
    They're strings? That isn't HTML in the DOM? Commented Sep 4, 2013 at 20:54
  • 3
    so how do you tell the difference between the text that you want and the text that you don't want? Commented Sep 4, 2013 at 20:54
  • 1
    You could definitely avoid using regex for most of this - get the source of the image, strip the extension; append that to the class list of the previous cell; use a regex to strip out the unwanted text. Commented Sep 4, 2013 at 20:55
  • 2
    Do you have a regex that you think should work, and doesn't? We are more willing to help fix your code than to write the code for you. Commented Sep 4, 2013 at 20:56
  • Do you plan to perform your replacements with javascript in the browser? Commented Sep 4, 2013 at 20:57

2 Answers 2

2

You probably need to provide a lot more details about what you need to do, but the best course of action would be to use a DOM parser and JavaScript has a very nice one built in (IE8- is not supported).

// Select all odd `td` nodes and iterate over them
Array.prototype.forEach.call(document.querySelectorAll("td:nth-child(odd)"),
function (elem) {
    // Get the immediately following sibling (with the img)
    var imgTd = elem.nextSibling;
    // Get the color from the <img>
    elem.className += ' ' + imgTd.querySelector("img").getAttribute("src")
        .replace('.png', '');
    // Remove the sibling
    imgTd.parentNode.removeChild(imgTd);
    // Update the initial elements text to remove the undesired text
    elem.textContent = elem.textContent.replace("TextI Do NOtWant", "");
});

http://jsfiddle.net/e9vrK/

Sign up to request clarification or add additional context in comments.

1 Comment

I think this is the closest to what I need. I will try it out, and let you know
0

Id do this with jquery, something like:

var td;
var img;
var color;
 $('img').each(function(){
   img=$(this);
   td = img.closest('td').prev();
   color = img.attr('src').split('.')[0]
     td.html('the image is '+color+'.png').addClass(color);
 });

demo here http://jsfiddle.net/QHkbe/2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.