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

7
  • What do you do with the temp variable after setting it? Commented Dec 11, 2014 at 12:33
  • I want to output it to a pdf using jspdf, but it does not understand HTML codes, and I am planning to output the line separately after a split. Commented Dec 11, 2014 at 12:34
  • what is an example of the contents you are trying to modify? and what is the expected result? You want to keep the first opening div and the last closing div? Commented Dec 11, 2014 at 12:34
  • 2
    So you are currently logging temp to the console or something and that's how you know the replace isn't working? Or...? Commented Dec 11, 2014 at 12:35
  • 1
    jsfiddle.net/k9pxe3qg Commented Dec 11, 2014 at 12:37

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

6 Comments

It should be noted that this only replaces the first occurence of </div><div>, you'll have to use Gaurang Tandon's solution to replace them all.
Yes as Drown said, it only replaces the first occurence, and I need to replace all
Thank you Javier! I suppose it didn't work because I put a " on the Regexp
you are welcome :), as you see if you quoted the regExp y treated as normal string
$(function(){ var text="132|233|424"; var temp = text.replace("|",","); alert(temp); }); expected result is 132,233,424 but its returning 132,233|424
|
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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.