简体   繁体   中英

JavaScript RegExp what was matched

I have a string and I need to find out what was matched in the string. For example:

var txt = "Hello world!";
txt.replace(/[a-h]/gi, '<span>' + TEXT_MATCHED + '</span');

I would like the output to be... <span>H</span><span>e</span>llo worl<span>d</span>!

try

var txt = "Hello world!";
txt.replace(/([a-h])/gi, "<span>$1</span>");

(step 1: group the matched stuff using brackets. step 2: use $1 for the first matched group)

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