Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/448.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 - Fatal编程技术网

使用Javascript在字符串中查找多个匹配项

使用Javascript在字符串中查找多个匹配项,javascript,Javascript,我想做的就是做这样的事情 string = 'I\'m a value with "quotes1" that could have other "quotes2" at the same time' 找到所有“”的位置并将其放入数组 我当前拥有的代码格式不正确,试图使用两个变量来查找两个要使用的点。大致如此 function quoteslice(com) { if (com.indexOf('"') !== -1) { slicepoint1 = com.index

我想做的就是做这样的事情

string = 'I\'m a value with "quotes1" that could have other "quotes2" at the same time'
找到所有“”的位置并将其放入数组

我当前拥有的代码格式不正确,试图使用两个变量来查找两个要使用的点。大致如此

function quoteslice(com) {
    if (com.indexOf('"') !== -1) {
        slicepoint1 = com.indexOf('"');
        com = com.slice(0,slicepoint1 + 1);
        slicepoint2 = com.indexOf('"');
        com = com.slice(0, slicepoint2);
        return com;
    } else {
        return com;
    }
}
尝试使用:

否则,如果要获取str中的第一个带引号的字符串,可以使用正则表达式:

var quotedString = str.replace(/^[\s\S]*?('.*?')[\s\S]*$/, '$1');

转义字符\不计数

您是否尝试自己实现此功能?看起来你只是让别人帮你做这项工作。你到底在哪里遇到了问题?你尝试过什么吗?比如说split刚刚找到了我自己的解决方案来解决我需要做的事情。split,但这不适用于一开始问的问题,所以我会为尝试同样事情的人打开这个窗口。我已经用indexOf发布了一个答案。我很确定indexOf会更快…在Chrome的调试中测试了这一点,我必须提醒未来的代码用户注意转义字符不会被计数。尝试将其放入调试器,变量“array”不会吐出任何字符results@WhiteFusion我现在已经改正了。
var quotedString = str.replace(/^[\s\S]*?('.*?')[\s\S]*$/, '$1');
var str = 'I\'m a value with "quotes1" that could have other "quotes2" at the same time';
var res = [];
for(var i=0; i < str.length; i++) { 
  if(str[i]==='"') { res.push(i) } 
}