0

I have the string test1 test2 tes<span style="color:red;">t3</span> span test4 and I want to put span tag surrounding the span word which position is after </span> without touching the existing span tag using javascript regex.

5
  • 3
    That sounds like manipulating HTML, which shouldn't really be done with regex, but with something that can actually parse HTML. Commented Jul 30, 2014 at 16:51
  • str.replace('span', '<span>span</span>')? Commented Jul 30, 2014 at 16:51
  • @pattmorter - and that would replace the first span only, giving test1 test2 tes<<span>span</span> style ... Commented Jul 30, 2014 at 16:52
  • @adeno you're right... idk what i was thinking haha. Commented Jul 30, 2014 at 16:53
  • str.replace(' span ', ' <span>span</span> ') ? With spaces surrounding span word. Commented Jul 30, 2014 at 16:54

1 Answer 1

1

REgex:

(<\/span> )(span)

REplacement string:

$1<span>$2</span>

DEMO

> 'test1 test2 tes<span style="color:red;">t3</span> span test4'.replace(/(<\/span> )(span)/g, "$1<span>$2</span>")
'test1 test2 tes<span style="color:red;">t3</span> <span>span</span> test4'
Sign up to request clarification or add additional context in comments.

2 Comments

For the current example your answer is correct, but lets think more golabaly. I want to do the same think but with any word or part of word that is close to the text from the span tag. For example pa from span
That is close but the result I want is this: 'test1 test2 tes<span style="color:red;">t3</span> s<span>pa</span>n test4' is it possible?

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.