gpt4 book ai didi

JavaScript 正则表达式搜索

转载 作者:行者123 更新时间:2023-12-03 10:27:48 25 4
gpt4 key购买 nike

我通过网站生成了以下代码。我正在寻找的是脚本根据一组关键字扫描文本变量,如果找到任何关键字,则将其传递给变量。如果找到两个关键字,则将两个关键字用连字符连接起来并传递给变量。我还需要动态设置“var str”。例如,“var str == VAR10”。 VAR10 将有一个动态文本来搜索关键字。

var re = /Geo|Pete|Rob|Nick|Bel|Sam|/g;
var str = 'Sam maybe late today. Nick on call. ';
var m;

if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
}

在上面的代码中,Sam 和 Nick 是我想要连字符连接并传递给 VAR10 的两个关键字。

最佳答案

If two keywords are found, both are joined by a hyphen and passed to a variable

为了清楚起见,请尝试对原始代码进行此更新:

var re = /Geo|Pete|Rob|Nick|Bel|Sam/g;
var str = 'Sam maybe late today. Nick on call. ';
var m;
var VAR10 = ""; // holds the names found

if ((m = re.exec(str)) !== null) {
var name1 = m;

if ((m = re.exec(str)) !== null) {
var name2 = m;
// Two names were found, so hyphenate them
// Assign name1 + "-" + name2 to the var that you want
VAR10 = name1 + "-" + name2;
} else {
// In the case only one name was found:
// Assign name1 to the var that you want
VAR10 = name1;
}
}

注意,更改

var re = /Geo|Pete|Rob|Nick|Bel|Sam|/g;

var re = /Geo|Pete|Rob|Nick|Bel|Sam/g;

这是更新的演示:http://jsfiddle.net/7zg2hnt6/1/

关于JavaScript 正则表达式搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29337907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com