Skip to content Skip to sidebar Skip to footer

Replace All Content Between Characters With Javascript

I'm attempting to make a simple markdown converter to get better at JS and Regex. I now need to find everything between two asterisks, and wrap them in tags: JSFIDDLE va

Solution 1:

You can use a capture group to get the content that should be wrapped in the HTML tags:

var html = html.replace(/\*([^*]+)\*/g , '<i>$1</i>');

Explanation of ([^*]+):

(        # startof capture group
  [^     # startof negated character class (matchanycharacternot listed)
    *    # literal asterisk character
  ]      # endof negated character class
  +      # matchat least oneof the previous token
)        # endof capture group

So [^*]+ means "match at least one character that is not *". This has the effect that all characters up to the next * are matched.

Solution 2:

You can match part of the string and then use that in the replace call as documented in https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Example.3A_Using_a_regular_expression_to_change_data_format

Example:

'*abc is a string*'.replace(/\*([\w\s]+)\*/g, '<i>$1</i>')
> '<i>abc is a string</i>'

Solution 3:

Alternatively use adjusted greediness in your regexp (+? in my pattern below), though it is less performant (see http://blog.stevenlevithan.com/archives/greedy-lazy-performance). Next try using callback:

var result = source.replace( /(*|_)(.+?)(\1)/g, function( all, starter, content, ender ) {
    return"<i>" + content + "</i>";
} );

Using callback might improve your code's flexibility:

var result = source.replace( /(*|_)(.+?)(\1)/g, function( all, starter, content, ender ) {
    switch ( starter ) {
        case'*' :
            return"<strong>" + content + "</strong>";
        case'_' :
            return"<em>" + content + "</em>";
    }
} );

Post a Comment for "Replace All Content Between Characters With Javascript"