Thereissoupinmyfly
Thereissoupinmyfly

Reputation: 244

How to use regex (in JS) match words and include html tags

Amateur at JavaScript here. I set my self-projects to help myself learn. I usually find the answers on stackoverflow but several days of googling have not enlightened me on the following. I’m trying to match whole words in sentences. I plan to do this to wrap the words in <span> tags. The regex I’m using is

  (\/?+<?+\w+<?+>?+) 

seen in use here http://regex101.com/r/nT2yY4

If this code is run on the string this is a <span>string</span> It returns

  1. this
  2. is
  3. a
  4. <span>
  5. string<
  6. /span>

I'd like it to return

  1. this
  2. is
  3. a
  4. <span>string</span>

while the string <span>two words</span> returns

  1. <span>two
  2. words</span>

also I'd like punctuation pulled split off as well so "this is a string." becomes

  1. this
  2. is
  3. a
  4. string
  5. .

Upvotes: 0

Views: 750

Answers (3)

Stephan
Stephan

Reputation: 43053

Try this regex instead:

/([\w<>\/]+|\.)/g

Description

Regular expression visualization

Demo

http://regex101.com/r/rJ4rR8

Upvotes: 1

Gaurang Tandon
Gaurang Tandon

Reputation: 6761

If you want this is a <span>string</span> to be split at white space, use:

"this is a <span>string</span>".split(" ");

which gives you:

[ 'this', 'is', 'a', '<span>string</span>' ]

Upvotes: 1

Ian Routledge
Ian Routledge

Reputation: 4042

It looks to me like all you care about is the spaces and not the tags, so can't you just use something like:

/([^\W]+)/g

To split on whitespace.

If I test that on "This is a sentence with some words and also multiple words sometimes" then the result is, I think, what you've asked for.

Upvotes: 1

Related Questions