0

The code in question is as follow:

  <head>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script>
    var convert = function(){
        var str = $('#input')[0].value;
        n=str.replace("p","div");
        $("#output")[0].value = n;
    }
    </script>
  </head>
  <body>
  <textarea style="width:600px;height:800px;float:left" id="input"></textarea>
  <textarea style="width:600px;height:800px" id="output"></textarea>
  <button onclick="convert();" style="width:60px;height=40px">convert</button>

I intend to use this code to get input from users, and replace all "p"s in it with "div". However, if the input has multi lines, the output will be exactly the same with the input. So I went searching about how to manipulate multiline strings in javascript. I did found sth. but they are mostly about how to create a new string variable with known multi line strings, and none of them is helpful for my problem.

It seems to me the user input multi line string has been successfully assigned to str in the function, the problem is str.replace() doesn't work as I expect. Is this because str is a multiline string?(And is str a multiline string(I'm not even sure about this)?) If yes, how can I make this happen?

shenkwen
  • 2,994
  • 5
  • 31
  • 65
  • By the way, it looks like you haven't accepted an answer on any of the questions you've posted on Stack Overflow. It's a nice thing to do and rewards you some reputation points, also! Just click the checkmark to the left of your favorite answer on a post. More on this here: http://stackoverflow.com/tour – m59 Jan 07 '14 at 03:51

1 Answers1

0

Are you just looking for a global replacement?

n=str.replace(/p/g,"div");

Live demo here (click). All "p"s typed into the input are converted to "div", no matter what line they are on.

Here's some documentation on str.replace(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

m59
  • 41,346
  • 14
  • 107
  • 131
  • Thank you for your swift answer, giving my first acceptance to you. – shenkwen Jan 07 '14 at 04:53
  • So my code was only replacing the first occurence of "p" but not all of them. I didn't even realize it and thought it didn't work at all because of multi line string. Anyway, I use your code and it works just fine. But here comes new question: I read through the instrction of replace() method and accordingly changed my code to n=str.replace("p","div","g"), but still, only the first occurence of "p" is being replaced. What went wrong? Thank you again. – shenkwen Jan 07 '14 at 05:06
  • OK. Standard replace() doesn't have a 3rd param, I get it. – shenkwen Jan 08 '14 at 15:36