Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

php - Remove HTML tags from javascript output

I looked around stackoverflow but I couldn't find an answer that solved my problem. I hope I can explain it so you all understand what I'm trying to do... (If more info is needed, please let me know).

I have a piece PHP script that adds and removes content from an session array. Right now this is the code for this script:

<?php foreach ($_SESSION['products'] as $product): ?>
    <p style="font-size:1.2rem"><?php echo htmlspecialchars($product); ?></p>
<?php endforeach;?>

Using Javascript I echo this to a textarea where it returns the values.

Javascript

$('.my-subject').click(function(){
    var title = $(this).attr('value');
      $("textarea#thema").html(data); 
})

Right now it returns the value with the HTML Tags <p>...</p>. How can I get it to return the value's with no HTML tags and a line break at the end? I tried using:

$("textarea#thema").text() + '
';

But that didn't work, this still shows the <p>-tags and no line break.

I also saw some codes like this:

function removeTags(){
    var txt = document.getElementById('myString').value;
    var rex = /(<([^>]+)>)/ig;
    alert(txt.replace(rex , ""));
}

But I don't know if I can use that for my code and how to do this... Any help would be appreciated. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It sounds like data is a string containing markup in the form <p style="font-size:1.2rem">STUFF HERE</p>, repeated, and you want to get just the STUFF HERE part.

The reliable way to do that is to parse the HTML and extract the text from it:

// The data
var data =
    '<p style="font-size:1.2rem">First</p>' +
    '<p style="font-size:1.2rem">Second</p>' +
    '<p style="font-size:1.2rem">Third</p>';
// Parse it
var elements = $.parseHTML(data);
// Convert that to an array of the text of the entries
var entries = elements.map(function(element) {
  return $(element).text();
});
// Get a string of the array entries joined with "
"
var value = entries.join("
");
// Done!
$("#output").val(value);
<textarea id="output" rows="4"></textarea>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...