我正在尝试用HTML,CSS和Javascript编写一些东西。
我在使用正则表达式时遇到了一些问题。

让我举一个简单的例子来解释我的问题,因为我找不到解决方案。



<script>
var str = "I am <b>a tennis player</b> but  I like also playing <i>football</i> and <i>rugby</i>, I am  <b>34</b> years old, I like <u>cooking</u> even if there is nothing in common with <i>tennis</i>, <i>football</i> or <i>rugby</i>.";

var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
   return val.replace(/<\/?b>/g,'');
});

alert(result)

</script>





因此,您可能已经猜到了,我正在寻找标记<b></b>,<i></i>,<u></u>之间的所有文本。为了更清楚,我希望能够选择“ a tennis player”,“ football”,“ rubgy”,“ 34”,“ cooking”等。

目前,我只处理了一个标签。当我尝试几个失败时。我没有使用正则表达式的经验(我没有在该领域学习和工作),在互联网上找到的课程也没有回答我的问题。我认为合并三个正则表达式并不困难,但是我迷惑不解地使用AND或OR等。:/

最佳答案

参见下面的代码:



var str = "I am <b>a tennis player</b> but  I like also playing <i>football</i> and <i>rugby</i>, I am  <b>34</b> years old, I like <u>cooking</u> even if there is nothing in common with <i>tennis</i>, <i>football</i> or <i>rugby</i>.";

var result = str.match(/<(b|i|u)>(.*?)<\/\1>/g).map(function(val){
   return val.replace(/<\/?b>|<\/?i>|<\/?u>/g,'');
});

alert(result)

关于javascript - 使用正则表达式在javascript中的几种不同类型的标签之间选择文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34724195/

10-14 17:16
查看更多