如何在2个字符串之间获取字符串并添加到arrray

时间:2018-06-13 03:03:34

标签: javascript

我有一个字符串:

 let str = ' some text url:"http:/myURL01", some text url:"http:/myURL02", ..., url:"http:/myURL03", some text';

现在,我想获取所有URL(url:"和"之间的子字符串)并添加到数组

期待结果:arrURL ["myURL01", "myURL02", "myURL03"]

谢谢!

4 个答案:

答案 0 :(得分:2)

尝试以下

var str = ' some text url:"http:/myURL01", some text url:"http:/myURL02", ..., url:"http:/myURL03", some text';
    var arr = [];
	var x=0;
	do
	{
		x = str.indexOf("url:", x);
		if(x!=-1)
		{	
			arr.push(str.substring(x+5,  str.indexOf(",",x)-1))
			x = x+1;
		}
	}
	while(x!=-1);

  console.log(arr)

答案 1 :(得分:2)

let str = ' some text url:"http:/myURL01", some text url:"http:/myURL02", ..., url:"http:/myURL03", some text';
results = str.match(/http.*?(?=\")/g);
console.log(results);

正则表达式解释 - https://regex101.com/r/CMiWcr/1/

答案 2 :(得分:0)

只需使用拆分

    let str = ' some text url:"http:/myURL01", some text url:"http:/myURL02", ..., url:"http:/myURL03", some text';

    var arrURL = str.split(",");    
    var i;
    for (i = 0; i < arrURL .length; i++) {
        arrURL[i] = arrURL[i].split("url:").pop();
    }

答案 3 :(得分:0)

$(document).ready(
    function() {
        var str = ' some text url:"http:/myURL01", some text 
    url:"http:/myURL02", ..., url:"http:/myURL03", some text';
        var trg = new Array();
        $('#elementId').click(function() {
            var list = str.split("http:/");
            for (var i = 1; i < list.length; i++) {
                var elementStr = list[i].split('"');
                trg[i - 1] = '"http:/'+elementStr[0]+'"';
            }
        });
    });

其中'elementId'是触发事件的元素id