janoliver
janoliver

Reputation: 7824

replacing linebreaks in javascript doesn't work :(

Hey there, I'm trying to replace a

<blockquote>...</blockquote>

with

>> ...

This is my Code:

var testhtml = 'sdkjhfbs <blockquote>skldfjsfkjghbs\n sdjkfhb ksdbhv isl\n kdjbhdfgkj bs</blockquote>kdjfgnkdfj';
alert(blockquoteConvert(testhtml));

function blockquoteConvert(html) {
    return '>>' + html.
        replace(/<blockquote>([^]+)<\/blockquote>/gi,"$1").
        replace('/\n/','\n>> ');
}

But it doesn't find the Linebreaks. (I checked with indexOf('\n')).

How can I do this ?

Upvotes: 2

Views: 315

Answers (6)

janoliver
janoliver

Reputation: 7824

Okay, now I'm confused. Try this please:

var testhtml = 'sdkjhfbs <blockquote>skldfjsfkjghbs\n sdjkfhb ksdbhv isl\n kdjbhdfgkj bs</blockquote>kdjfgnkdfj';
alert(convertLineBreaks(testhtml));
alert(blockquoteConvert(testhtml));

function blockquoteConvert(html) {
    return html
        .replace(/<blockquote>([^]+)<\/blockquote>/gi,convertLineBreaks("$1"));
}

function convertLineBreaks(text) {
    return '>>' + text.replace(/\n/g,'\n>> ');
}

After the replacement of blockquote, my linebreaks seem to be lost... ?

Upvotes: 0

streetparade
streetparade

Reputation: 32878

Try this

var testhtml = 'sdkjhfbs <blockquote>skldfjsfkjghbs\n sdjkfhb ksdbhv isl\n kdjbhdfgkj bs</blockquote>kdjfgnkdfj';
alert(blockquoteConvert(testhtml));

function blockquoteConvert(id) {
car text = document.getElementById(id).value;
text = text.replace(/\n\r?/g, '>>');
}


Or use jquery 
$('#caption').html($('#caption').text().replace(/\n\r?/g, '>>'));

Upvotes: 0

Jimmy
Jimmy

Reputation: 37081

You were close, but you weren't consistent with the syntax:

function blockquoteConvert(html) {
    return '>> ' + html.
        replace(/<blockquote>([^]+)<\/blockquote>/gi,"$1").
        replace(/\n/g,'\n>> ');
}

Upvotes: 0

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124758

You need to do a global replace, or otherwise the replace will match only the first newline. Also, you can't use quotes around your regular expression as the slashes will become part of the search string, so try this:

replace(/\n/g,'\n>> ')

Upvotes: 0

Gumbo
Gumbo

Reputation: 655129

Try it without the quotes:

replace(/\n/g,'\n>> ')

Now the delimiters are part of the literal regular expression declaration syntax and not part of the pattern itself.

Upvotes: 7

Pekka
Pekka

Reputation: 449385

Using a double backslash \\n should help.

Upvotes: 0

Related Questions