Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top