Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 动态搜索字符串两点之间的子字符串_Javascript_Jquery - Fatal编程技术网

Javascript 动态搜索字符串两点之间的子字符串

Javascript 动态搜索字符串两点之间的子字符串,javascript,jquery,Javascript,Jquery,如何在两个指定值之间的字符串中动态搜索和保存子字符串。 例如,如果a具有以下字符串集 var string1 = "This is.. my ..new string"; var string2 = "This is.. your ..new string"; 现在,如果我想保存两个点之间的子字符串,在本例中是“my”和“your”,那么该怎么办呢?从字符串中,可能保存在另一个变量中,或者删除除“my”之外的所有内容。我知道使用indexof(“my”)是可能的,但这不是动态的。正则表达式是解

如何在两个指定值之间的字符串中动态搜索和保存子字符串。 例如,如果a具有以下字符串集

var string1 = "This is.. my ..new string";
var string2 = "This is.. your ..new string";

现在,如果我想保存两个点之间的子字符串,在本例中是“my”和“your”,那么该怎么办呢?从字符串中,可能保存在另一个变量中,或者删除除“my”之外的所有内容。我知道使用indexof(“my”)是可能的,但这不是动态的。

正则表达式是解决此类问题的方法。你可以用谷歌搜索一下。那里有很多文档和教程

对于您的特定问题,要获取“.”之间的字符串,可以使用以下代码

var match1 = string1.match('\\.\\.\\s*(.+?)\\s*\\.\\.');
match1 = match1 ? match1[1] : false;
var match2 = string2.match('\\.\\.\\s*(.+?)\\s*\\.\\.');
match2 = match2 ? match2[1] : false;
试试这个脚本:D

/* I have escaped the dots | you can add the spaces in the delimiter if that is your delimiter like*/
var delimiter = '\\.\\.'; 
var text = "This is.. your ..new ..test.. string";

/* this will match anything between the delimiters and return an array of matched strings*/
var res = text.match(new RegExp(delimiter + '(.*?)' + delimiter,'g'));


/*res will be [' your ', 'test'] */
/* I just realized that it does not match "..new ..", which should be a valid match. */;

/* to remove the delimiter string from your results */
 for(i in res) { 
  res[i]=res[i].replace(new RegExp(delimiter,'g'),'');
 };
 console.log(res);

您应该学习如何使用正则表达式。这正是你所需要的。@thefourtheye是的,我为模式练习工作,总是有两个点……Regex就是你要找的。不要使用下面的“拆分”解决方案。根本没有说它不起作用“下面的拆分解决方案更容易理解。正则表达式很好,但不要让为这个极其简单的案例发布拆分解决方案的人删除他们完全有效的建议。它很简单
string1.split(…)[1]
不添加空格删除,直接在
match()之后使用
[]
总是一个坏主意,因为它假设匹配成功。如果不成功,它将出错。您应该首先检查匹配是否成功。@TwilightSun,这是给我的结果,我试图理解您所做的。我在正则表达式方面很弱。@TwilightSun现在可以理解了。。非常感谢:-)