简体   繁体   中英

Replace n patterns in a string

Is there an easy way to fix this code:

title_1 = $(this).closest('tr').find('td').html();
title_2 = $(this).closest('tr').find('td').next().html();
title_3 = $(this).closest('tr').find('td').next().next().html();

question = question.replace(/{title_1}/g, title_1);
question = question.replace(/{title_2}/g, title_2);
question = question.replace(/{title_3}/g, title_3);

So it isn't so dully (repeated) and can cover n occurences of title_ pattern?

I'm a beginner Javascript developer and a complete regular expressions newbie (actually, they scare me! :|), so I'm unable to do this by myself. I've tried to look for an inspiration in different languages , but failed.

String.prototype.replace() could take a function as second parameter.

var $this = $(this);
question = question.replace(/\{title_(\d+)\}/g, function(match, n) {
  return $this.closest('tr').find('td').eq(n - 1).html();
});

You can use a function in the replace, to get the value depending on what you find:

question = question.replace(/{title_(\d+)}/g, $.proxy(function(x, m){
  return $(this).closest('tr').find('td:eq('+(m-1)+')').html();
}, this));

Demo: http://jsfiddle.net/n3qrL/

Demo Here

Try this , Generalized for getting all td tag's text value :

$("table").find("tr").each(function(){

 $(this).find("td").each(function(){
     alert($(this).html());
     var txt=$(this).html();
     //var pattern="/{"+txt+"}/g";
     //question = question.replace(pattern, txt);
 });
});

NB. In your question you have not mentioned the value for 'question' . please define value for 'question'

It seems to me that you want to get the text content of the first three cells of a table row and use it to replace the content of a string, and that this is an element somewhere in the row. So you can do:

var n = 3;  // number of cells to get the text of
var textArray = [];
var tr = $(this).closest('tr')[0];
var reString;

for (var i=0; i<n; i++) {
  reString = '{title_' + (i+1) + '}';
  question = question.replace(reString, tr.cells[i].textContent);
}

If you wish to avoid jQuery's closest , you can use a simple function like:

function upTo(el, tagName) {
  tagName = tagName.toLowerCase();
  do {
    el = el.parentNode;
    if (el.tagName && el.tagName.toLowerCase() == tagName) {
      return el;
    }
  } while (el.parentNode)
}

then:

var tr = upTo(this, 'tr');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM