获取用“/”分隔的单词"与Regex合作

Getting words separated by " / " with Regex

本文关键字:quot 合作 Regex 单词 分隔 获取      更新时间:2023-09-26

我有以下代码片段:

HTML

<div class="colors">
    <h1>Colors:</h1>
    
    <div class="recipe"></div>
</div>
<div class="numbers">
    <h1>Numbers:</h1>
    
    <div class="recipe"></div>
</div>
<div class="people">
    <h1>People:</h1>
    
    <div class="recipe"></div>
</div>

JavaScript

var colors = 'yellow / black / purple',
    numbers = '5 / 15 / 25',
    people = 'Brad Pitt / Leonardo DiCaprio / Anne Hathaway';
$('.colors .recipe').html(colors.replace(/('w+)'/*/g, '<em>$1</em><br>'));
$('.numbers .recipe').html(numbers.replace(/('w+)'/*/g, '<em>$1</em><br>'));
$('.people .recipe').html(people.replace(/('w+)'/*/g, '<em>$1</em><br>'));

在jsFiddle中查看

我不擅长正则表达式,然后在各自的食谱上呈现分离的值时,我会得到意想不到的结果(您可以在上面发布的jsFiddle上看到更多)。

我的意思是,下面的结果显示给我:

[…]

Brad

Pitt

/Leonardo

迪卡普里奥

[…]

我想要和需要的是:

Brad Pitt

莱昂纳多·迪卡普里奥

没有斜线,没有分开的名字/姓氏。

您不需要regex。拆分方法可以完成任务:

var colors = 'yellow / black / purple',
    numbers = '5 / 15 / 25',
    people = 'Brad Pitt / Leonardo DiCaprio / Anne Hathaway';
function wrapEm(e) {
    return "<em>" + e + "</em>";
}
people.split(" / ").join("<br/>");
$('.colors .recipe').html(colors.split(" / ").map(wrapEm).join("<br/>"));
$('.numbers .recipe').html(numbers.split(" / ").map(wrapEm).join("<br/>"));
$('.people .recipe').html(people.split(" / ").map(wrapEm).join("<br/>"));

拆分顾名思义,使用/作为分隔符将字符串拆分为一个数组。

将正则表达式替换为:

/([^'/]+)'/*/g

与其用('w+)来表示单词(不包括空格),不如用[^'/]+来表示除斜杠之外的任何含义。

此正则表达式非常适用:

 $('.colors .recipe').html(colors.replace(/('')?'//g, '<em>$1</em><br>'));