简体   繁体   中英

Convert Ruby String gsub! to javascript string replace method

I have snip code in Ruby that used gsub! method as below

# handle headings (H1-H6)
text.gsub!(/(<\/h[1-6]>)/i, "\n\\1") # move closing tags to new lines
text.gsub!(/[\s]*<h([1-6]+)[^>]*>[\s]*(.*)[\s]*<\/h[1-6]+>/i) do |s|
  hlevel = $1.to_i

  htext = $2
  htext.gsub!(/<br[\s]*\/?>/i, "\n") # handle <br>s
  htext.gsub!(/<\/?[^>]*>/i, '') # strip tags             
  hlength = 3

  case hlevel
    when 1   # H1, equal below
      htext = "\n" + htext.upcase + "\n" + ('=' * hlength)
    when 2   # H1, dashes below
      htext = "\n" + htext.upcase + "\n" + ('-' * hlength)
    else     # H3-H6, dashes below
      htext = "\n" + htext + "\n" + ('+' * hlength)
  end
  htext
end

Above snip will convert html string to plain text. this process for H(s) tag.

I need to port the snip to javascript that will use replace method Someone can help me, thanks

You might want to try this gist (JS implementation of gsub):

https://gist.github.com/varunkumar/8572487

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM