user1941729
user1941729

Reputation: 13

Replace text string with jQuery on page load?

I have following code in my html

<p>6565655655|cell</p>

I want to remove this vertical line and wrap word "cell" into round bracket. So I want output like below

<p>6565655655 (cell)</p>

How I can do it using jquery when content of p tag loading dynamically by ajax call.

Upvotes: 1

Views: 3008

Answers (5)

lukeocom
lukeocom

Reputation: 3243

If you add a class name to the paragraph tag then you could also use the following...

html part -

<p class="item">6565655655|cell</p>

jQuery part

$(document).ready(function() {
var aText = ($('.item').html()).split('|');
$('.item').html(aText[0] + "&nbsp;&#40;" + aText[1] + "&#41;");
});

Upvotes: 0

Travis J
Travis J

Reputation: 82297

in your ajax success method:

success: function(data)
{
 $(data).find("p").each(function(index,element){
  var pipe = element.innerHTML.indexOf("|");
  if( pipe != -1 ){
   element.innerHTML.replace("|","( ");
   element.innerHTML += ")";
  }
 }
 //continue with placing data on the page.
}

you could also farm this out into a function so you could call it when the page first loads too

function replacePipe(element)
{
  $(element).find("p").each(function(index,el){
  var pipe = el.innerHTML.indexOf("|");
  if( pipe != -1 ){
   el.innerHTML.replace("|","( ");
   el.innerHTML += ")";
  }
 }
}

which would make the ajax success look like this:

success: function(data)
{
 replacePipe(data);
 //place data, perhaps $(tar).html(data);
}

and you could do this onload too

window.onload = function(){ 
 replacePipe(document.body);
};

Upvotes: 0

PhearOfRayne
PhearOfRayne

Reputation: 5050

You could do it like this:

$('p').each(function () {
    var $txt = $(this).text();

    if ($txt.indexOf('|') > 0) {
        var txtArray = $txt.split('|');
        $(this).html(txtArray[0] + ' (' + txtArray[1] + ')');
    }
});

Example: http://jsfiddle.net/fewds/E637y/1/

Upvotes: 0

Chris
Chris

Reputation: 769

Split the content of the p-tag with the pipe as delimiter and re-insert the so created array, second element with surrounding bracket.

Here an example:

var splittedString = $("p").text().split("|");
$("p").html(splittedString[0] + " (" + splittedString[1] + ")");

jsFiddle: http://jsfiddle.net/r3c4J/

Upvotes: 1

user234932
user234932

Reputation:

Few ways to do it:

var text = '6565655655|cell';

Method 1:

var parts = text.split('|');
$('p').text(parts[0] + ' (' + parts[1] + ')');

Method 2:

$('p').text(text.replace('|cell', ' (cell)');

Method 3:

$('p').text(text.replace(/([0-9]+)\|(.*)/, '$1 ($2)'));

Upvotes: 0

Related Questions