简体   繁体   中英

Replace text inside a HTML element using jQuery

I have a page template which uses PHP to pull data from an external website and it uses HTML to render the page layout.

Some of the data being pulled can't be changed at the source. So I need to change it on the actual website, as it's rendered.

The data I need changed is essentially a "status". And is coded as follows:

<span id="property-status"><?php echo $property['status']; ?></span>

There are three types of status coming from the source, and they are:

SOLD, CLOSED, and ACTIVE

I need to change SOLD and CLOSED to FUNDED.

The question is how do I achieve this using jQuery when the developers can't change it on their end.

If is a string .Try with regex /\\>(.*?)\\</gmi and String.replace() function

 var obj ={'sold':'found','closed':'found'}; var a ='<span id="property-status">CLOSED</span>'; var res = a.replace(/\\>(.*?)\\</gmi,((a,b)=> '>'+obj[b.toLowerCase()]+'<')); console.log(res) 

Or with html use trim() remove unwanted space

 var obj ={'sold':'found','closed':'found'}; $('#property-status').text(obj[$('#property-status').text().trim().toLowerCase()]) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span id="property-status">sold </span> 

Sure, you can do it on client-side by comparing the element's text like below:

 $(document).ready(function() { // Your element var status = $("#property-status"); // It's text without spaces and to uppercase, for the comparison var status_text = status.text().trim().toUpperCase(); if (status_text == "SOLD" || status_text == "CLOSED") { status.text("FUNDED"); } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span id="property-status">Sold</span> 


But! ... You also could do it on server-side, with a PHP function:

<?php
function fixStatus($status){

  // Text without space and to uppercase
  $status_to_compare = trim(strtoupper(status));

  if($status_to_compare=="CLOSED" || $status_to_compare=="SOLD"){
    return "FUNDED";
  }else{
    return $status;
  }
}
?>

<span id="property-status"><?php echo fixStatus($property['status']); ?></span>

PHPFiddle

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