Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting line breaks in text quoted in javascript

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!

like image 351
grace Avatar asked May 12 '26 03:05

grace


1 Answers

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:

/
/

like image 175
mkoryak Avatar answered May 14 '26 17:05

mkoryak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!