John Emerson
John Emerson

Reputation: 55

JS replace using Regex

I want to paste formatted text taken from Word or similar, or copied from a web page, into an HTML5 textarea by stripping the formatting but retaining the line breaks.

Tried extracting the raw text and then trying to use regex and js.replace to insert linebreaks where we have a lower case letter followed by a full-stop followed by an upper-case letter.

    var txt = $('#bio').text();
    txt = txt.replace([a-z.][A-Z],'.<br>');
    $('#bio').html(txt);

Result in the console is: "Uncaught SyntaxError: Unexpected token ]"

I expected the result to be a line break in the HTML at each paragraph.

Upvotes: 0

Views: 56

Answers (2)

Djaouad
Djaouad

Reputation: 22766

Your regex should be enclosed within //, still, I don't think you have a valid regex for this task, use this instead (as a start at least):

var txt = $('#bio').text();
txt = txt.replace(/([a-z])\.([A-Z])/g, '$1.<br>$2');
$('#bio').html(txt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p id="bio">
  A paragraph.Another paragraph.Yet another paragraph.
</p>

Explanation:

Replace:

/         // start of regex
 (        // start of 1st group
  [a-z]   // one lowercase letter
 )        // end of 1st group
 \.       // one . (it needs to be escaped to be matched literally)
 (        // start of 2nd group
  [A-Z]   // one uppercase letter
 )        // end of 2nd group
/         // end of regex
g         // global flag, in order to replace all matches

With:

$1    // the match from the 1st group (the lowercase letter)
.<br> // .<br> literally
$2    // the match from the 2nd group (the uppercase letter)

Upvotes: 3

mwilson
mwilson

Reputation: 12900

Your syntax is off. You need to wrap your regex with /<regex>/

*I'm not sure what you're trying to accomplish with your regex, but this will get you past the Uncaught SyntaxError: Unexpected token ] error *

var txt = $('#bio').text();
txt = txt.replace(/[a-z.][A-Z]/,'.<br>');
$('#bio').html(txt);

If you're having trouble getting your RegEx correct, I'd recommend using this tool: https://regex101.com/

Upvotes: 2

Related Questions