1

I have a string that looks like this:

<script> some random script, maybe even some line breaks\ </script>

or even

<script type="random/type" src="https://even_a_source.com"> random scripts </script>

I would like to insert a class tag in the script part, like this:

<script class="addMe" type="random/type" src="https://even_a_source.com"> random scripts </script>

without changing the rest of the script tag.

I figured using regex would be a good start: /<[^>]*>/ matches <script> and </script> I think but I didn't progress further unfortunately.

As mentioned in the comments, using the gem nokogiri might be easier to deal with this, I'm trying it right now and update this if I find the solution.

3
  • 2
    Using regex for processing html/xml is generally considered a bad idea. Use something like nokogiri instead: github.com/sparklemotion/nokogiri Commented May 20, 2020 at 15:50
  • Thanks, I'm looking at the docs right now and I see that you can modify attributes with this gem. I'll try this and keep this thread updated! Commented May 20, 2020 at 15:55
  • I personally think this question wouldn't be facing a close vote if it contained some actual ruby code Commented May 20, 2020 at 17:05

2 Answers 2

1

With nokogiri you can manipulate it easily:

doc = Nokogiri.parse('<script> some random script, maybe even some line breaks\ </script>')
doc.children.first.set_attribute('type', 'random/type')
doc.children.to_s

=> "<script type=\"random/type\"> some random script, maybe even some line breaks\\ </script>"
Sign up to request clarification or add additional context in comments.

Comments

0

This is really easy using Nokogiri gem.

After installing the gem here is the code that worked for me:

require 'nokogiri'

@doc = Nokogiri::HTML::DocumentFragment.parse <<-EOHTML

<script>
    random scripts
</script>
EOHTML

script  = @doc.at_css "script"
script['class'] = 'addMe'

puts @doc.to_html

This outputs the following in the console:

<script class="addMe">
    random scripts
</script>

I just have to figure out a way to fit this in my code but this shouldn't be a problem.

This closes the question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.