0

Hi I am trying to change the contents of a hidden input.

var temp = $("#header").val().replace("(/<\/div><div>/g","<br>");

I tried using the following replace but it does not change it.

May I know what I did wrong? I am trying to replace:

</div><div>

to

<br>

EDIT - this is my program flow

  • User enters input to a wysiwyg text editor which produces the output

  • Save the user input to database

  • Go to another page where the wysiwyg input is retrieved from database and save it to input type hidden

  • Replace the </div><div> to a <br> which is then outputted to a div

wirey00
  • 33,149
  • 7
  • 51
  • 64
RickyHalim
  • 285
  • 5
  • 22

2 Answers2

1

To replace all ocurrences in a string, the correct syntax with regExp is:

var temp = $("#header").val().replace(/<\/div><div>/g,"<br>");

You can test it, here:

'</div><div></div><div></div><div></div><div>'.replace(/<\/div><div>/g,"<br>");

returns:

<br><br><br><br>
Javier del Saz
  • 846
  • 1
  • 8
  • 16
  • It should be noted that this only replaces the first occurence of `
    `, you'll have to use Gaurang Tandon's solution to replace them all.
    – Drown Dec 11 '14 at 12:34
  • Yes as Drown said, it only replaces the first occurence, and I need to replace all – RickyHalim Dec 11 '14 at 12:35
  • Thank you Javier! I suppose it didn't work because I put a " on the Regexp – RickyHalim Dec 11 '14 at 12:43
  • you are welcome :), as you see if you quoted the regExp y treated as normal string – Javier del Saz Dec 11 '14 at 12:49
  • $(function(){ var text="132|233|424"; var temp = text.replace("|",","); alert(temp); }); expected result is 132,233,424 but its returning 132,233|424 – ravithejag Aug 16 '17 at 07:11
  • You need a regExp to replace all occurrences, based on w3c documentation: Note: If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier (see "More Examples" below). Source: https://www.w3schools.com/jsreF/jsref_replace.asp – Javier del Saz Aug 17 '17 at 08:15
0

You should do:

.replace(/<\/div><div>/g,"<br>");

The RegExp should not be enclosed within quotes else it would be a String. Also, the .val() method is used for textareas. Use .html() for header, divs, etc.

putvande
  • 14,686
  • 3
  • 31
  • 50
Gaurang Tandon
  • 6,110
  • 10
  • 44
  • 79
  • Hi, thanks for the response. Sorry I was using input type hidden not textarea, I wrote wrong. However after I change to your code, it still does not work – RickyHalim Dec 11 '14 at 12:33