开发者

splitting a string in js where a pattern DOES NOT match?

开发者 https://www.devze.com 2023-01-23 01:19 出处:网络
i am trying to split a TextArea value where a pattern does not match the text is like following: Some Good Tutorials

i am trying to split a TextArea value where a pattern does not match

the text is like following:

Some Good Tutorials
http://a.com/page1
http://a.com/page2
Some Good Images
http://i.com/p1
http://i.com/p2
Some Good Videos
http://m.com/p1
http://m.com/p2

now i want to get only the links from the text so a better solution would be to split the whole string in an array of strings where the a line is not a url and then from amongst this array split each string with "\n"

edit:

okay i found a solution, i can find lines which does not begin with http:// or https:// and replace them with a good place holder after than i can get the links though i am weak in regex so can someon开发者_Python百科e tell me how to do this in javascript?


Match the pattern. don't split with it.

value=value.match(/http\:\/\/.+/g)

(.+matches everything to the end of a line)


Solved finally! Here is the code:

function split_lines() {
    var oText = $('linkTxtArea').value;
    removeBlankLines(); // a helper function to remove blank lines
    oText = oText.split("\n"); // first split the string into an array
    for (i = 0; i < oText.length; i++) // loop over the array
    {
        if (!oText[i].match(/^http:/)) // check to see if the line does not begins with http:
        {
            oText[i] = oText[i].replace(oText[i], "!replaced!"); // replace it with '!replaced!'
        }
    }
    oText = oText.toString().split("!replaced!"); // now join the array to a string and then split that string by '!replaced!'
    for (i = 1; i < oText.length; i++)
    {
        oText[i] = oText[i].replace(/^,/,"").replace(/,$/,""); // there were some extra commas left so i fixed it
    }
    return oText;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号