mguz
mguz

Reputation: 77

JavaScript storing search matches in array

How to store the search matches from id="post_body" to array?

<textarea name="post[body]" id="post_body">

--Lorem ipsum-- dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et --Dolore-- magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. --Duis aute-- irure dolor in reprehenderit in voluptate velit esse cillum --Dolore-- eu fugiat nulla pariatur

</textarea>

The target are all words surrounded by '--'. In Ruby, I do that with:

matches = tex.scan(/--(.+?)--/).flatten
matches = matches.uniq

In this case, the array would be:

matches = ["Lorem ipsum", "Dolore", "Duis aute"];

NB: the word "Dolore" appears twice surrounded with --, but in the array it should be stored only once.

Upvotes: 3

Views: 231

Answers (2)

Udith Gunaratna
Udith Gunaratna

Reputation: 2111

    var text = document.getElementById('post_body').value;
    var res = text.match(/--\w+\s*\w*--/g);

     //remove duplicates
    uniqueArray = res.filter(function(item, pos, self) {
      return self.indexOf(item) == pos;
    });

     //remove "--" parts
    finalArray = uniqueArray.map(function(item) {
      return item.replace(/--/g,"");
    });

    alert(finalArray);
<textarea name="post[body]" id="post_body">--Lorem ipsum-- dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et --Dolore-- magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. --Duis aute-- irure dolor in reprehenderit in voluptate velit esse cillum --Dolore-- eu fugiat nulla pariatur</textarea>

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You may use the following code:

function contains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
}

var re = /--\s*(.*?)\s*--/g; 
var str = '--Lorem ipsum-- dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et --Dolore-- magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. --Duis aute-- irure dolor in reprehenderit in voluptate velit esse cillum --Dolore-- eu fugiat nulla pariatur';
var arr = [];
while ((m = re.exec(str)) !== null) {
    if (!contains(arr, m[1]))
    { 
        arr.push(m[1]);
    }
 }
alert(arr);

The regex will match the text enclosed in -- and place the first capture group text into the array arr only if the value does not exist in the array (the contains function is taken from this SO post).

As for regex, \s* added to --\s*(.*?)\s*-- will trim the value inside. Remove these \s*s if you do not need trimming.

Upvotes: 1

Related Questions