Meek
Meek

Reputation: 3348

Replace breaks and spaces with "+"

I have en element with a string of text where I need to replace spaces and line breaks with "+" in the second column. I have the following code: Markup:

<table id="tblData">
<tr>
<td>John Smith</td>
<td>114 text text text<br/>text, text,<br/>text text<br/>text
<td>N/A</td>
</tr>
</table>

Script:

$('#tblData td:nth-child(2)').each( function( index, element ){
console.log($(this).text()
     .replace(/ /g, '+')
     .replace('<br/>', '+')
);
});

Replacing spaces is working fine, but replacing <br/> is not. What am I missing?

Fiddle here.

Upvotes: 1

Views: 551

Answers (3)

Anton
Anton

Reputation: 32581

Try this you need to replace \n aswell

console.log($(this).html()
              .replace(/(<br>| |\n|\r)/g, '+')
           );

DEMO

Upvotes: 2

Raidri
Raidri

Reputation: 17550

If you want to replace <br/> you have to use $(this).html() instead of $(this).text(). .text() will not output html tags. For the regular expression look at the other answers. A side effect of this is, that all other html tags in the text will still be there after the replacing.

Upvotes: 1

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

$('#tblData td:nth-child(2)').each( function( index, element ){
   console.log($(this).text()
     .replace(/ |\n|\n\r|\r\n/g, '+')// use /\s|\n|\n\r|\r\n for all spaces
  );
});

Fiddle

Upvotes: 0

Related Questions