最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to replace <p> tag with a comma symbol - Stack Overflow

programmeradmin2浏览0评论

I have a hidden field with a value <p>Copy 1</p><p>Copy 2</p><p>Copy 3</p><p>Copy 4</p>. I would like to replace the </p> tags with a ma symbol and remove the <p> tags so that the final output will be Copy 1,Copy 2,Copy 3,Copy 4. I tried using the JavaScript replace('<p>','') function, but I couldn't remove it.

I have a hidden field with a value <p>Copy 1</p><p>Copy 2</p><p>Copy 3</p><p>Copy 4</p>. I would like to replace the </p> tags with a ma symbol and remove the <p> tags so that the final output will be Copy 1,Copy 2,Copy 3,Copy 4. I tried using the JavaScript replace('<p>','') function, but I couldn't remove it.

Share Improve this question edited Dec 19, 2013 at 12:11 JJJ 33.2k20 gold badges94 silver badges103 bronze badges asked Dec 19, 2013 at 12:05 NibinNibin 3,9602 gold badges21 silver badges40 bronze badges 2
  • Could you show us your code? – Magnus Engdal Commented Dec 19, 2013 at 12:07
  • 1 Maybe your <p> are actually &lt;p&gt;? – MaGnetas Commented Dec 19, 2013 at 12:08
Add a ment  | 

4 Answers 4

Reset to default 6

Use the map function, and then join the array with ', '.

$.map(
    $('<p>Copy 1</p><p>Copy 2</p><p>Copy 3</p><p>Copy 4</p>'), 
    function(val, i) { 
       return val.innerHTML; 
    }).join(', ');

If you need to do it with .replace, you can do it like this (note that this does not rely on jQuery):

var stringToTest = "<p>Copy 1</p><p>Copy 2</p><p>Copy 3</p><p>Copy 4</p>";

stringToTest = stringToTest.replace(/<p>/g, "").replace(/<\/p>/g,",");

stringToTest = stringToTest.substr(0, stringToTest.length - 1);

jsFiddle: http://jsfiddle/vTpV2/

".I tried using the javascript replace('<p>','') function."

If you want to do a global replace on a string you have to pass a regular expression with the global flag as the first argument. So:

var val = $("#idOfYourElementHere").val();

val = val.replace(/<\/p><p>/g, ', ')    // first swap <p></p> for mas
         .replace(/<\/?p>/g, '');       // then swap the leftover <p> and </p>
                                        // for empty strings (i.e., remove them)

You can try this:

var _sHFVal = _sHFVal.split('<p>').join("").split('</p>').join(',');
_sHFVal = _sHFVal.substring(-1, _sHFVal.length-1);
发布评论

评论列表(0)

  1. 暂无评论