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.
- Could you show us your code? – Magnus Engdal Commented Dec 19, 2013 at 12:07
- 1 Maybe your <p> are actually <p>? – MaGnetas Commented Dec 19, 2013 at 12:08
4 Answers
Reset to default 6Use 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);