3

Doing some text swapping (testimonials fade in/out) with JavaScript and want to insert the equivalent of a <br/> inside the quotes so the author of the quote is on the next line. In the below code, I tried following the instructions at JavaScript: How to add line breaks to an HTML textarea?, but am not sure how to insert /\n\r?/g to make it work.

<script type="text/javascript">
    var text = document.forms[0].txt.value;
    text = text.replace(/\n\r?/g, '<br />');
</script>

<script type="text/javascript">

    window.testimonials = [
        '"This was a great experience" /\n\r?/g - Max Cameron, ThinkTank',
        '"This was a great experience" /\n\r?/g - Max Cameron, ThinkTank',
        "source code"
    ];
</script>

Is there any way to force it onto the next line? Thanks!

Community
  • 1
  • 1
grace
  • 73
  • 7
  • if you are inserting the `/\n\r?/g` (as it sounds you are) why not just use the text you DO want (`
    `) or, are those testimonials coming from a source you cannot edit?
    – Robot Woods May 22 '12 at 00:26

2 Answers2

3

you are doing something really weird here. why are you inserting a 'regex' into your variables?

fiddle:
http://jsfiddle.net/4Fheu/

try this:

<script type="text/javascript">
    var text = window.testimonial; // or maybe: document.forms[0].txt.value;
    text = text.replace(/\n\r?/g, '<br />');
    alert(text);
</script>

<script type="text/javascript">

    window.testimonials = [
        '"This was a great experience" \n - Max Cameron, ThinkTank',
        '"This was a great experience" \n - Max Cameron, ThinkTank',
        "source code"
    ];
</script>

/\n\r?/ is a regex that says: 'newline' followed by 0 or 1 'carriage return'.

the value '/\n\r?/' is a string that might look like this:

/
/

mkoryak
  • 57,086
  • 61
  • 201
  • 257
0

Borrowing from what you linked to:

window.testimonials = [
'"This was a great experience" /\n\r?/g - Max Cameron, ThinkTank'.replace(/(\n\r?)|(,)/g, '<br />');,
'"This was a great experience" /\n\r?/g - Max Cameron, ThinkTank'.replace(/(\n\r?)|(,)/g, '<br />');,
"source code"];
Community
  • 1
  • 1
qwertymk
  • 34,200
  • 28
  • 121
  • 184
  • hm, that completely breaks the text swapping functionality. Is there any other way? – grace May 22 '12 at 00:32
  • Still no go :\ Is there any other script you recommend for swapping testimonials with a fade transition? – grace May 22 '12 at 00:43
  • It's not working because you're putting regex into a string. If you remove the `/`, and the `?/g` from the string.. it should work. – Daedalus May 22 '12 at 02:38