-2

Please help me cause I'm noob in programming. What should I do to make it replace all string matches? If I write /http://example.com/ad//g instead of "http://example.com/ad/" it won't run properly either.

<!DOCTYPE html>
<html>
<body>

<h3>Instert your links</h3>

input:<br>
<textarea id="myTextarea">
http://example.com/ad/123.html
http://example.com/ad/345.html
http://example.com/ad/3567.html
</textarea>



<button type="button" onclick="myFunction()">Get clean links</button>

<p id="links"></p>

<script>
function myFunction() {
    var x = document.getElementById("myTextarea").value;
    var x = x.replace("http://example.com/ad/", "http://example.com/story/"); 
    var x = x.replace("\n","</br>");
    document.getElementById("links").innerHTML = x;
}
</script>

</body>
</html>

4 Answers4

1

Since you can't provide the global flag to String.prototype.replace directly, you need to provide it to the RegExp you pass as the first argument:

x.replace(/\n/g, '</br>')

If you don't care about using the original value in the replacement, you can continue passing a string as the second argument.

<!DOCTYPE html>
<html>
<body>

<h3>Instert your links</h3>

input:<br>
<textarea id="myTextarea">
http://example.com/ad/123.html
http://example.com/ad/345.html
http://example.com/ad/3567.html
</textarea>



<button type="button" onclick="myFunction()">Get clean links</button>

<p id="links"></p>

<script>
function myFunction() {
    var x = document.getElementById("myTextarea").value;
    var x = x.replace(/http:\/\/example.com\/ad\//g, "http://example./com/story/"); 
    var x = x.replace(/\n/g,"</br>");
    document.getElementById("links").innerHTML = x;
}
</script>

</body>
</html>
ssube
  • 47,010
  • 7
  • 103
  • 140
0

You need to use a regex with the Global flag:

x = x.replace(/http:\/\/example\.com\/ad\//g, "http://example.com/story/"); 
x = x.replace(/\n/g,"</br>");

Note that you need to escape any special characters.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

The g flag should work fine. Your problem when trying to use regex may relate to the fact that / needs to be escaped in JavaScript regex literals. Try this:

document.getElementById("links").innerHTML = document.getElementById("myTextarea")
  .value
  .replace(/http:\/\/example\.com\/ad\//g, "http://example.com/story/")
  .replace(/\n/g, "<br>");
Jacob
  • 77,566
  • 24
  • 149
  • 228
0

replace function will only replace the first ocurrence:

Taked from: http://www.w3schools.com/jsref/jsref_replace.asp

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).

To perform a global replace you should use a regular expression in the first parameter of replace function. In your case:

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

I hope it can help you!

agurodriguez
  • 480
  • 2
  • 6
  • 19