用字符串替换标签名称

可以说我有一些HTML代码,例如:

"Hello, my <strong>name</strong> is Nanoo."

How could I replace the <strong> tag with a string?

例如:

"Hello, my **name** is Nanoo."

(Replaces the <strong> tag with **)

I could probably use the replace() function, however I want to do this efficiently.
Thanks for any help.

评论
  • ousman
    ousman 回复

    Use a regular expression. ((.+?) is used to capture the contents of the strong tag, so we can use $1 in the replacement to substitute the captured group.)

    However, don't use regexps to really parse HTML.

    >>> s = "Hello, my <strong>name</strong> is Nanoo.";
    >>> s.replace(/<strong>(.+?)<\/strong>/g, '**$1**');
    "Hello, my **name** is Nanoo."