简体   繁体   中英

Regex Replacing Characters with HTML Tags

I have this sample string where I would like to replace the star with an opening and closing strong tag using regular expressions in JavaScript:

To increase search results, use the 8** prefix.
877 and 866 will result in more matches than 800 and 888 prefixes.
*Note*: The pattern for a custom number can be more than 7 digits. For example: 1-800-Mat-tres(s)

The ideal output would be:

To increase search results, use the 8** prefix.
877 and 866 will result in more matches than 800 and 888 prefixes.
<strong>Note</strong>: The pattern for a custom number can be more than 7 digits. For example: 1-800-Mat-tres(s)

The only caveat being that if there are two starts in a row (like 8**), that they not be replaced with the strong tags.

Thank you in advance for any assistance.

Maybe you could try something like this?

\*(\S[^\*]+\S)\*

The + means 1 or more, so will only match if there is something between the * .

The [^\\*] means anything that's not a star * .

UPDATE I've updated the regex above to specify that it doesn't match nonwhite space character's in between the * and and the first and last characters of each match. This prevent's the highlighted bit below from incorrectly matching:

8* * prefix. 877 and 866 will result in more matches than 800 and 888 prefixes. * * prefix. 877 and 866 will result in more matches than 800 and 888 prefixes. * * prefix. 877 and 866 will result in more matches than 800 and 888 prefixes. * Note*

Here is the same regex with comments (in javascript)

"\\*" +       // Match the character “*” literally
"\\S" +       // Match a single character that is a “non-whitespace character”
"[^\\*]" +    // Match any character that is NOT a * character
   "+" +        // Between one and unlimited times, as many times as possible, giving back as needed (greedy)
"\\S" +       // Match a single character that is a “non-whitespace character”
"\\*"         // Match the character “*” literally

Finally, here is an example of the javascript you could use:

yourStringData.replace(/\*(\S[^\*]+\S)\*/g, "<strong>$1</strong>");

Just replace the yourStringData with a variable containing the data you want to run the replace against.

如果*之间总是有单词

your_string.replace(/\*(\w+)\*/g, "<strong>$1</strong>");

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