El Bandito
El Bandito

Reputation: 55

RegEx - Extract words that contains a substring, from a comma seperated string

Using Javascript / jQuery, I have the following string;

MasterString = "typography,caret,car,card,align,shopping-cart,adjust,allineate";

What's the best RegEx for extracting all the words that contains e.g. "car", so I have the following string left;

ResultString = "caret,car,card,shopping-cart";

And is it also possible to extract only the first word, that contains "car"?

ResultString = "caret";

I am writing a simple search-routine, which matches the query (car) against a comma seperated list and I want to show the first result as the outcome for the query.


UPDATE

I tried the simple RegEx mentioned in the answer below;

[^,]*car[^,]*

It works perfect, see this (test-)image - https://i.sstatic.net/q22is.png

The query is "car" and all icons tagged with a word that contains at least "car" are made visible in the search-results.

The only problem is that the search-string "car" is always different (depends on user input in the search-form). So how can I enter a variable match-string in the RegEx above?

Something like this;

[^,]*%QUERY-FROM-SEARCHFIELD%[^,]*

Upvotes: 3

Views: 5077

Answers (2)

hjpotter92
hjpotter92

Reputation: 80657

You can do so without regex:

  1. Split the string to an array:

    var tempArray = MasterString.split( ',' );
    
  2. Filter the array for values which contain the word car in it:

    tempArray = tempArray.filter(function (x) {
        if (x.contains('car')) return x;
    });
    
  3. Join the resulting array back:

    ResultString = tempArray.join( ',' );
    

MasterString = "typography,caret,car,card,align,shopping-cart,adjust,allineate";
var tempArray = MasterString.split( ',' );
tempArray = tempArray.filter(function (x) {
    if (x.contains('car')) return x;
});
ResultString = tempArray.join( ',' );

To get the first result, simply access the 0th element of tempArray:

var x = tempArray[0];

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174836

You could try the below regex to match only the strings caret,car,card,shopping-cart,

[^,]*car[^,]*

DEMO

> var masterString = "typography,caret,car,card,align,shopping-cart,adjust,allineate";
undefined
> masterString.match(/[^,]*car[^,]*/g);
[ 'caret',
  'car',
  'card',
  'shopping-cart' ]

To match the first word which contains the string car, you need to remove the global flag from the pattern.

> masterString.match(/[^,]*car[^,]*/);
[ 'caret',
  index: 11,
  input: 'typography,caret,car,card,align,shopping-cart,adjust,allineate' ]

Now convert the array into a string delimited by comma and stored it into a variable.

> var resultString = masterString.match(/[^,]*car[^,]*/g).join(",");
undefined
> resultString
'caret,car,card,shopping-cart'

Upvotes: 2

Related Questions