【问题标题】:How can I transfer every line which starts with specific patterns to the end of the string?如何将以特定模式开头的每一行转移到字符串的末尾?
【发布时间】:2016-01-22 06:48:14
【问题描述】:

我有一个这样的字符串:

var str = " this is a [link][1]
            [1]: http://example.com
            and this is a [good website][2] in my opinion
            [2]: http://goodwebsite.com
            [3]: http://example.com/fsadf.jpg
            [![this is a photo][3]][3]
            and there is some text hare ..! ";

现在我想要这个:

var newstr = "this is a [link][1]
              and this is a [good website][2] in my opinion
              [![this is a photo][3]][3]
              and there is some text hare ..!


                [1]: http://example.com
                [2]: http://goodwebsite.com
                [3]: http://example.com/fsadf.jpg"

我该怎么做?


实际上,那个变量str 是一个textarea 的值......我正在尝试创建一个markdown 编辑器......所以我想要的与SO 的textarea 所做的完全一样。


这是我的尝试:

/^(\[[0-9]*]:.*$)/g 在第一行选择[any digit]:

我认为我应该使用() 为它创建一个组,然后用\n\n $1 替换它

【问题讨论】:

  • and there is some text hare ..! 去哪儿了?
  • @WiktorStribiżew 谢谢,我编辑了它

标签: javascript regex


【解决方案1】:

试试这个:

strLinksArray = str.match(/(\[\d+\]\:\s*[^\s\n]+)/g);
strWithoutLinks = str.replace(/(\[\d+\]\:\s*[^\s\n]+)/g, ''); //removed all links

在这里,您将获得不带链接的数组和字符串形式的链接,然后进行任何您想要的更改。

【讨论】:

  • emm 我不知道我是否可以使用它,但是您的解决方案似乎很有用..! +1
【解决方案2】:

你可以使用

var re = /^(\[[0-9]*]:)\s*(.*)\r?\n?/gm;                // Regex declaration
var str = 'this is a [link][1]\n[1]: http://example.com\nand this is a [good website][2] in my opinion\n[2]: http://goodwebsite.com\n[3]: http://example.com/fsadf.jpg\n[![this is a photo][3]][3]\nand there is some text hare ..!';
var links = [];                                      // Array for the links
var result = str.replace(re, function (m, g1, g2) {  // Removing the links
  links.push("  " + g1 + " " + g2);                        // and saving inside callback
	return "";                                   // Removal happens here 
});
var to_add = links.join("\n");                   // Join the links into a string
document.getElementById("tinput").value = result + "\n\n\n" + to_add; // Display
<textarea id="tinput"></textarea>

请参阅 regex101.com 上的regex demo

正则表达式解释

  • ^ - 行首(由于 /m 修饰符)
  • (\[[0-9]*]:) - 第 1 组(在替换回调中称为 g1)匹配...
    • \[ - 左方括号
    • [0-9]* - 零个或多个数字
    • ] - 右方括号
    • : - 冒号
  • \s* - 零个或多个空格
  • (.*) - 第 2 组匹配 (g2) 除换行符以外的零个或多个字符
  • \r?\n? - 一或零 \r 后跟一或零 \n
  • /gm - 定义全局搜索和替换,^ 匹配行开始而不是字符串开始

【讨论】:

  • 完美..!只是一件事..如何在[1]:[2]:[3]: 后面添加两个空格?
  • 啊哈,你现在说 before,我将 behind 理解为 after :) 我更新了答案以反映这一点.
  • 如果您将链接数组保持在全局级别,则无需查找“最大数字”,您将在links.length 中找到它。
  • . 不匹配换行符。贪婪的.* 子模式将始终匹配到行尾并在第一个换行符处停止。因此,它是多余的。
  • Limiting quantifier 救援:\s{0,3} 将匹配 0 到 3 个空格。
猜你喜欢
  • 1970-01-01
  • 2011-07-26
  • 2021-11-10
  • 1970-01-01
  • 2019-11-05
  • 1970-01-01
  • 2017-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多