简体   繁体   English

Javascript正则表达式替换并将找到的所有元素添加到数组

[英]Javascript Regex Replace And Add All Element Found To An Array

currently I am very confused! 目前我很困惑! I have been trying to solve this for a while, and can't seem to crack it. 我一直在尝试解决这个问题,似乎无法破解。 I can't even find an answer on Google. 我什至无法在Google上找到答案。

Currently I am using this Regex I wrote in Javascript: 目前,我正在使用用Java语言编写的Regex:

((?: {4,}|\t+)(?:.*))

Simply, it matches everything that is 4+ spaces out or 1+ tabs out in a textarea. 简而言之,它匹配文本区域中4个以上空格或1个以上制表符的所有内容。 Yea, that sounds familiar you say? 是的,这听起来很耳熟? It is simply what Stack Overflow does for codeblocks. 这只是Stack Overflow对代码块所做的。 Now, I have run in to an issue. 现在,我遇到了一个问题。

Basically I am wanting to replace all of these instances found in the textarea, but first I want to back them up to an array. 基本上,我想替换在textarea中找到的所有这些实例,但是首先,我想将它们备份到数组中。 Now, I am not sure how I grab each match found, and insert it in to the array. 现在,我不确定如何抓取找到的每个匹配项,并将其插入到数组中。

Here is what I have so far: 这是我到目前为止的内容:

.replace(/((?: {4,}|\t+)(?:.*))/gi, function (m, g1, g2) {
    return //STUCK HERE
}); //Matches Bold

So simply, I just want to grab all matches found in a textarea (Either indented or 4 spaces) and then I would like to add the contents of the match to an array. 简而言之,我只想获取文本区域中找到的所有匹配项(缩进或4个空格),然后将匹配项的内容添加到数组中。 How would I go about doing this? 我将如何去做呢? Please Help! 请帮忙!

If you want to get the array of matches, you can use match() function : 如果要获取匹配项array ,可以使用match()函数:

var matchesArray = $('textarea').val().match('/((?: {4,}|\t+)(?:.*))/gi');

and if you want to replace, use simple replace() function : 如果要替换,请使用简单的replace()函数:

$('textarea').val().replace('/((?: {4,}|\t+)(?:.*))/gi', 'replaceWith');

Hope this helps. 希望这可以帮助。

You can hit two targets with one bullet: 您可以用一颗子弹击中两个目标:

var items = [];
var re = /((?: {4,}|\t+)(?:.*))/g;
textarea.value = textarea.value.replace(re, function ($0, $1) {
    items.push($1);
    return 'replacement';
});

If you want to get the code blocks back then: 如果您想找回代码块,则:

var codeLines = [];
var reMarkers = /\{\{(.*?)\}\}/g;
var reCodeBlocks = /((?: {4,}|\t+)(?:.*))/g;
var text = textarea.value;

// save and remove code blocks
text = text.replace(reCodeBlocks, function ($0, $1) {
    var marker = '{{' + codeLines.length + '}}';
    codeLines.push($1);
    return marker;
});

// revert to previous state
text = text.replace(reMarkers, function ($0, $1) {
    return codeLines[parseInt($1, 10)];
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM