-1

I have a regular expression to search in a string.

new RegExp("\\b"+searchText+"\\b", "i")

My strings:

"You are likely to find [[children]] in [[a school]]"
"[[school]] is for [[learning]]"

How can I search only the words in double brackets?

A regular expression should contain searchText as a function argument.

XTRUST.ORG
  • 3,280
  • 4
  • 34
  • 60

3 Answers3

4

This RegEx will give you the basics of what you want:

\[\[[^\]]*\]\]
  • \[\[ matches the two starting brackets. A bracket is a special character in RegEx, hence it must be escaped with \
  • [^\]]* is a negated set that matches zero or more of any character except a closing bracket. This matches the content in-between the brackets.
  • \]\] matches the two closing brackets.

Here's a very basic example of what you could do with this:

let string = "You are likely to find [[children]] in [[a school]]<br>[[school]] is for [[learning]]";

string = string.replace(/\[\[[^\]]*\]\]/g, x => `<mark>${x}</mark>`);

document.body.innerHTML = string;
Toastrackenigma
  • 7,604
  • 4
  • 45
  • 55
3

You can use this regex:

var str = `-- You are likely to find [[children]] in [[a school]]
-- [[school]] is for [[learning]]`;
var regex = /(?<=(\[\[))([\w\s]*)(?=(\]\]))/gm;
var match = str.match(regex);
console.log(match);
protoproto
  • 2,081
  • 1
  • 13
  • 13
1

const re = /(?<=\[\[)[^\]]+(?=]])/gm
const string = `-- You are likely to find [[children]] in [[a school]]
-- [[school]] is for [[learning]]`

console.log(string.match(re))

const replacement = {
  children: 'adults',
  'a school': 'a home',
  school: 'home',
  learning: 'rest',
}

console.log(string.split(/(?<=\[\[)[^\]]+(?=]])/).map((part, index) => part + (replacement[string.match(re)[index]] || '')).join(''))
Piterden
  • 771
  • 5
  • 17
  • https://github.com/Piterden/js-create-includes-webpack-plugin/blob/master/js-create-includes-webpack-plugin.js – Piterden Oct 08 '18 at 05:41