简体   繁体   中英

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. .

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.

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>' ]

Try this regex instead:

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

Description

正则表达式可视化

Demo

http://regex101.com/r/rJ4rR8

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