在js中拆分一个模式不匹配的字符串? [英] splitting a string in js where a pattern DOES NOT match?

查看:95
本文介绍了在js中拆分一个模式不匹配的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试拆分模式不匹配的TextArea值

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

文本如下:

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

现在我想只从文本中获取链接以便更好解决方案是将整个字符串拆分为一个字符串数组,其中a行不是url,然后从这个数组中将每个字符串拆分为\ n

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"

编辑

好的我找到了解决方案,我可以找到不以http://或https://开头的行用一个好的占位符替换它们之后我可以获得链接
虽然我在正则表达式中很弱但是有人能告诉我如何在javascript中执行此操作吗?

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 someone tell me how to do this in javascript?

推荐答案

终于解决了!以下是代码:

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

这篇关于在js中拆分一个模式不匹配的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆