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

时间:2014-02-23 13:18:37

标签: javascript

我正在尝试做的是这样的事情

string = 'I\'m a value with "quotes1" that could have other "quotes2" at the same time'

找到所有'''的位置并将其放入数组中。

我目前拥有的代码格式不正确,并且尝试使用两个变量来查找两个点以使用.slice()。大概这个。

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;
    }
}

2 个答案:

答案 0 :(得分: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) } 
}

转义字符(\)计算

答案 1 :(得分:0)

尝试使用indexOf()

var string = 'I\'m a value with "quotes1" that could have other "quotes2" at the same time';
var pos = 0;
var array = [];

while ((pos = string.indexOf("'", pos)) > -1) {
    array.push(++pos);
}

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

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