Regex to match string with or without apostrophe












3















I am highlighting words in search results by using the query that user enters. Some of the results contain symbols like apostrophes and I would like to make the highlighting work if the apostrophe is entered or not. So, if I have this search result



Patrick O'Hagan



And user enters



O'Hagan



Or



Ohagan



It should match the highlighted part: Patrick O'Hagan



One way to achieve this that I thought of was to build a regex by insert a not required apostrophe after each character that user entered, so query ohagan would be translated to this regex:



/(o[']?h[']?a[']?g[']?a[']?n[']?)/gi


This works but there must be a better way?



EDIT:
Example I provided previously was not clear, so I will just provide an example code that should show what I want to achieve:



    var resultText = 'Patrick O'Hagan';
var query1 = 'o'hagan';
var query2 = 'ohagan';

var regex1 = this.buildRegex(query1);
var regex2 = this.buildRegex(query2);

var highlightedText1 = resultText.replace(regex1, x => `<b>${x}</b>`);
var highlightedText2 = resultText.replace(regex2, x => `<b>${x}</b>`);

console.log(highlightedText1); //prints: Patrick <b>O'Hagan</b>;
console.log(highlightedText2); //prints: Patrick <b>O'Hagan</b>;


What I am looking for is the buildRegex function which would construct a regular expression that would match the query in resultText but would ignore the apostrophes.










share|improve this question




















  • 2





    Yes, new RegExp(search.replace(/'/g, ''), 'i'). Remove all ' from the search text.

    – Wiktor Stribiżew
    Jan 2 at 7:57













  • I need it to highlight the original string with the apostrophe. I might be misunderstanding what you are trying to say but I think that you are suggesting to just remove the apostrophe from both the search result and the search query?

    – user1242967
    Jan 2 at 8:04











  • Use the includes method then. If string.includes(“‘”) {do something}

    – Lloyd Nicholson
    Jan 2 at 8:08






  • 1





    How exactly do you want to "highlight" the substring with the apostrophe?

    – CertainPerformance
    Jan 2 at 8:09











  • Then please edit the question to explain what you really want to achieve.

    – Wiktor Stribiżew
    Jan 2 at 8:10
















3















I am highlighting words in search results by using the query that user enters. Some of the results contain symbols like apostrophes and I would like to make the highlighting work if the apostrophe is entered or not. So, if I have this search result



Patrick O'Hagan



And user enters



O'Hagan



Or



Ohagan



It should match the highlighted part: Patrick O'Hagan



One way to achieve this that I thought of was to build a regex by insert a not required apostrophe after each character that user entered, so query ohagan would be translated to this regex:



/(o[']?h[']?a[']?g[']?a[']?n[']?)/gi


This works but there must be a better way?



EDIT:
Example I provided previously was not clear, so I will just provide an example code that should show what I want to achieve:



    var resultText = 'Patrick O'Hagan';
var query1 = 'o'hagan';
var query2 = 'ohagan';

var regex1 = this.buildRegex(query1);
var regex2 = this.buildRegex(query2);

var highlightedText1 = resultText.replace(regex1, x => `<b>${x}</b>`);
var highlightedText2 = resultText.replace(regex2, x => `<b>${x}</b>`);

console.log(highlightedText1); //prints: Patrick <b>O'Hagan</b>;
console.log(highlightedText2); //prints: Patrick <b>O'Hagan</b>;


What I am looking for is the buildRegex function which would construct a regular expression that would match the query in resultText but would ignore the apostrophes.










share|improve this question




















  • 2





    Yes, new RegExp(search.replace(/'/g, ''), 'i'). Remove all ' from the search text.

    – Wiktor Stribiżew
    Jan 2 at 7:57













  • I need it to highlight the original string with the apostrophe. I might be misunderstanding what you are trying to say but I think that you are suggesting to just remove the apostrophe from both the search result and the search query?

    – user1242967
    Jan 2 at 8:04











  • Use the includes method then. If string.includes(“‘”) {do something}

    – Lloyd Nicholson
    Jan 2 at 8:08






  • 1





    How exactly do you want to "highlight" the substring with the apostrophe?

    – CertainPerformance
    Jan 2 at 8:09











  • Then please edit the question to explain what you really want to achieve.

    – Wiktor Stribiżew
    Jan 2 at 8:10














3












3








3


0






I am highlighting words in search results by using the query that user enters. Some of the results contain symbols like apostrophes and I would like to make the highlighting work if the apostrophe is entered or not. So, if I have this search result



Patrick O'Hagan



And user enters



O'Hagan



Or



Ohagan



It should match the highlighted part: Patrick O'Hagan



One way to achieve this that I thought of was to build a regex by insert a not required apostrophe after each character that user entered, so query ohagan would be translated to this regex:



/(o[']?h[']?a[']?g[']?a[']?n[']?)/gi


This works but there must be a better way?



EDIT:
Example I provided previously was not clear, so I will just provide an example code that should show what I want to achieve:



    var resultText = 'Patrick O'Hagan';
var query1 = 'o'hagan';
var query2 = 'ohagan';

var regex1 = this.buildRegex(query1);
var regex2 = this.buildRegex(query2);

var highlightedText1 = resultText.replace(regex1, x => `<b>${x}</b>`);
var highlightedText2 = resultText.replace(regex2, x => `<b>${x}</b>`);

console.log(highlightedText1); //prints: Patrick <b>O'Hagan</b>;
console.log(highlightedText2); //prints: Patrick <b>O'Hagan</b>;


What I am looking for is the buildRegex function which would construct a regular expression that would match the query in resultText but would ignore the apostrophes.










share|improve this question
















I am highlighting words in search results by using the query that user enters. Some of the results contain symbols like apostrophes and I would like to make the highlighting work if the apostrophe is entered or not. So, if I have this search result



Patrick O'Hagan



And user enters



O'Hagan



Or



Ohagan



It should match the highlighted part: Patrick O'Hagan



One way to achieve this that I thought of was to build a regex by insert a not required apostrophe after each character that user entered, so query ohagan would be translated to this regex:



/(o[']?h[']?a[']?g[']?a[']?n[']?)/gi


This works but there must be a better way?



EDIT:
Example I provided previously was not clear, so I will just provide an example code that should show what I want to achieve:



    var resultText = 'Patrick O'Hagan';
var query1 = 'o'hagan';
var query2 = 'ohagan';

var regex1 = this.buildRegex(query1);
var regex2 = this.buildRegex(query2);

var highlightedText1 = resultText.replace(regex1, x => `<b>${x}</b>`);
var highlightedText2 = resultText.replace(regex2, x => `<b>${x}</b>`);

console.log(highlightedText1); //prints: Patrick <b>O'Hagan</b>;
console.log(highlightedText2); //prints: Patrick <b>O'Hagan</b>;


What I am looking for is the buildRegex function which would construct a regular expression that would match the query in resultText but would ignore the apostrophes.







javascript regex






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 at 8:28







user1242967

















asked Jan 2 at 7:55









user1242967user1242967

56711225




56711225








  • 2





    Yes, new RegExp(search.replace(/'/g, ''), 'i'). Remove all ' from the search text.

    – Wiktor Stribiżew
    Jan 2 at 7:57













  • I need it to highlight the original string with the apostrophe. I might be misunderstanding what you are trying to say but I think that you are suggesting to just remove the apostrophe from both the search result and the search query?

    – user1242967
    Jan 2 at 8:04











  • Use the includes method then. If string.includes(“‘”) {do something}

    – Lloyd Nicholson
    Jan 2 at 8:08






  • 1





    How exactly do you want to "highlight" the substring with the apostrophe?

    – CertainPerformance
    Jan 2 at 8:09











  • Then please edit the question to explain what you really want to achieve.

    – Wiktor Stribiżew
    Jan 2 at 8:10














  • 2





    Yes, new RegExp(search.replace(/'/g, ''), 'i'). Remove all ' from the search text.

    – Wiktor Stribiżew
    Jan 2 at 7:57













  • I need it to highlight the original string with the apostrophe. I might be misunderstanding what you are trying to say but I think that you are suggesting to just remove the apostrophe from both the search result and the search query?

    – user1242967
    Jan 2 at 8:04











  • Use the includes method then. If string.includes(“‘”) {do something}

    – Lloyd Nicholson
    Jan 2 at 8:08






  • 1





    How exactly do you want to "highlight" the substring with the apostrophe?

    – CertainPerformance
    Jan 2 at 8:09











  • Then please edit the question to explain what you really want to achieve.

    – Wiktor Stribiżew
    Jan 2 at 8:10








2




2





Yes, new RegExp(search.replace(/'/g, ''), 'i'). Remove all ' from the search text.

– Wiktor Stribiżew
Jan 2 at 7:57







Yes, new RegExp(search.replace(/'/g, ''), 'i'). Remove all ' from the search text.

– Wiktor Stribiżew
Jan 2 at 7:57















I need it to highlight the original string with the apostrophe. I might be misunderstanding what you are trying to say but I think that you are suggesting to just remove the apostrophe from both the search result and the search query?

– user1242967
Jan 2 at 8:04





I need it to highlight the original string with the apostrophe. I might be misunderstanding what you are trying to say but I think that you are suggesting to just remove the apostrophe from both the search result and the search query?

– user1242967
Jan 2 at 8:04













Use the includes method then. If string.includes(“‘”) {do something}

– Lloyd Nicholson
Jan 2 at 8:08





Use the includes method then. If string.includes(“‘”) {do something}

– Lloyd Nicholson
Jan 2 at 8:08




1




1





How exactly do you want to "highlight" the substring with the apostrophe?

– CertainPerformance
Jan 2 at 8:09





How exactly do you want to "highlight" the substring with the apostrophe?

– CertainPerformance
Jan 2 at 8:09













Then please edit the question to explain what you really want to achieve.

– Wiktor Stribiżew
Jan 2 at 8:10





Then please edit the question to explain what you really want to achieve.

– Wiktor Stribiżew
Jan 2 at 8:10












1 Answer
1






active

oldest

votes


















0















Alternation | for each character



Either the character OR the character followed by an apostrophe





  1. split() the keyword (ex. obrien) into an array of characters:



    var searchLetters = keyword.split('')

    // ['o','b','r','i','e','n']



  2. map() each character into a regex string that will accept either the ${literal match} OR| the ${literal match} followed by a single smart quote: [’ or a single straight quote: ']:



    var regexStrings = searchLetters.map(function(character) {
    return `(${character}|${character}['’])`;
    });

    // [`(${o}|${o}['’])`,`(${b}|${b}['’])`,`(${r}|${r}['’])`...]



  3. Next, join() the new array of regex strings into a single regex string and use it in a RegExp Object:



    var singleRegex = regexStrings.join('');
    var regexObject = new RegExp(`(${singleRegex})`, `gi`);



  4. That RegExp Object will be used to wrap whatever matches with a <mark> tag:



    var hits = targetContent.innerHTML.replace(regexObject, `<mark>$1</mark>`);





Demo






document.getElementById('search').addEventListener('change', function(e) {
highlight(this.value, '#content');
});

function highlight(keyword, selector) {
var node = document.querySelector(selector);
var html = node.innerHTML;
var clean = html.replace(/(<mark>|</mark>)/, '');
var escaped = keyword.replace(/[.*+?^${}()|[]\]/gi, '\$&');
var letters = escaped.split('').map(function(letter) {
return `(${letter}|${letter}['’])`;
});
var string = letters.join('');
var regex = new RegExp(`(${string})`, `gi`);
var hits = clean.replace(regex, `<mark>$1</mark>`);
node.innerHTML = hits;
}

<input id='search' type='search'><input type='button' value='search'>

<article id='content'>
<p>Murphy, Kelly, O’Sullivan, Walsh, Smith, O’Brien, Byrne, Ryan, O’Connor, O’Neill, O’Reilly, Doyle, McCarthy, Gallagher, O’Doherty, Kennedy, Lynch, Murray, Quinn, Moore, McLoughlin, O’Carroll, Connolly, Daly, O’Connell, Wilson, Dunne, Brennan, Burke, Collins, Campbell, Clarke, Johnston, Hughes, O’Farrell, Fitzgerald, Brown, Martin, Maguire, Nolan, Flynn, Thompson, O’Callaghan, O’Donnell, Duffy, O’Mahony, Boyle, Healy, O’Shea, White, Sweeney, Hayes, Kavanagh, Power, McGrath, Moran, Brady, Stewart, Casey, Foley, Fitzpatrick, O’Leary, McDonnell, MacMahon, Donnelly, Regan, Donovan, Burns, Flanagan, Mullan, Barry, Kane, Robinson, Cunningham, Griffin, Kenny, Sheehan, Ward, Whelan, Lyons, Reid, Graham, Higgins, Cullen, Keane, King, Maher, MacKenna, Bell, Scott, Hogan, O’Keeffe, Magee, MacNamara, MacDonald, MacDermott, Molony, O’Rourke, Buckley, O’Dwyer</p>
</article>








share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54002974%2fregex-to-match-string-with-or-without-apostrophe%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0















    Alternation | for each character



    Either the character OR the character followed by an apostrophe





    1. split() the keyword (ex. obrien) into an array of characters:



      var searchLetters = keyword.split('')

      // ['o','b','r','i','e','n']



    2. map() each character into a regex string that will accept either the ${literal match} OR| the ${literal match} followed by a single smart quote: [’ or a single straight quote: ']:



      var regexStrings = searchLetters.map(function(character) {
      return `(${character}|${character}['’])`;
      });

      // [`(${o}|${o}['’])`,`(${b}|${b}['’])`,`(${r}|${r}['’])`...]



    3. Next, join() the new array of regex strings into a single regex string and use it in a RegExp Object:



      var singleRegex = regexStrings.join('');
      var regexObject = new RegExp(`(${singleRegex})`, `gi`);



    4. That RegExp Object will be used to wrap whatever matches with a <mark> tag:



      var hits = targetContent.innerHTML.replace(regexObject, `<mark>$1</mark>`);





    Demo






    document.getElementById('search').addEventListener('change', function(e) {
    highlight(this.value, '#content');
    });

    function highlight(keyword, selector) {
    var node = document.querySelector(selector);
    var html = node.innerHTML;
    var clean = html.replace(/(<mark>|</mark>)/, '');
    var escaped = keyword.replace(/[.*+?^${}()|[]\]/gi, '\$&');
    var letters = escaped.split('').map(function(letter) {
    return `(${letter}|${letter}['’])`;
    });
    var string = letters.join('');
    var regex = new RegExp(`(${string})`, `gi`);
    var hits = clean.replace(regex, `<mark>$1</mark>`);
    node.innerHTML = hits;
    }

    <input id='search' type='search'><input type='button' value='search'>

    <article id='content'>
    <p>Murphy, Kelly, O’Sullivan, Walsh, Smith, O’Brien, Byrne, Ryan, O’Connor, O’Neill, O’Reilly, Doyle, McCarthy, Gallagher, O’Doherty, Kennedy, Lynch, Murray, Quinn, Moore, McLoughlin, O’Carroll, Connolly, Daly, O’Connell, Wilson, Dunne, Brennan, Burke, Collins, Campbell, Clarke, Johnston, Hughes, O’Farrell, Fitzgerald, Brown, Martin, Maguire, Nolan, Flynn, Thompson, O’Callaghan, O’Donnell, Duffy, O’Mahony, Boyle, Healy, O’Shea, White, Sweeney, Hayes, Kavanagh, Power, McGrath, Moran, Brady, Stewart, Casey, Foley, Fitzpatrick, O’Leary, McDonnell, MacMahon, Donnelly, Regan, Donovan, Burns, Flanagan, Mullan, Barry, Kane, Robinson, Cunningham, Griffin, Kenny, Sheehan, Ward, Whelan, Lyons, Reid, Graham, Higgins, Cullen, Keane, King, Maher, MacKenna, Bell, Scott, Hogan, O’Keeffe, Magee, MacNamara, MacDonald, MacDermott, Molony, O’Rourke, Buckley, O’Dwyer</p>
    </article>








    share|improve this answer




























      0















      Alternation | for each character



      Either the character OR the character followed by an apostrophe





      1. split() the keyword (ex. obrien) into an array of characters:



        var searchLetters = keyword.split('')

        // ['o','b','r','i','e','n']



      2. map() each character into a regex string that will accept either the ${literal match} OR| the ${literal match} followed by a single smart quote: [’ or a single straight quote: ']:



        var regexStrings = searchLetters.map(function(character) {
        return `(${character}|${character}['’])`;
        });

        // [`(${o}|${o}['’])`,`(${b}|${b}['’])`,`(${r}|${r}['’])`...]



      3. Next, join() the new array of regex strings into a single regex string and use it in a RegExp Object:



        var singleRegex = regexStrings.join('');
        var regexObject = new RegExp(`(${singleRegex})`, `gi`);



      4. That RegExp Object will be used to wrap whatever matches with a <mark> tag:



        var hits = targetContent.innerHTML.replace(regexObject, `<mark>$1</mark>`);





      Demo






      document.getElementById('search').addEventListener('change', function(e) {
      highlight(this.value, '#content');
      });

      function highlight(keyword, selector) {
      var node = document.querySelector(selector);
      var html = node.innerHTML;
      var clean = html.replace(/(<mark>|</mark>)/, '');
      var escaped = keyword.replace(/[.*+?^${}()|[]\]/gi, '\$&');
      var letters = escaped.split('').map(function(letter) {
      return `(${letter}|${letter}['’])`;
      });
      var string = letters.join('');
      var regex = new RegExp(`(${string})`, `gi`);
      var hits = clean.replace(regex, `<mark>$1</mark>`);
      node.innerHTML = hits;
      }

      <input id='search' type='search'><input type='button' value='search'>

      <article id='content'>
      <p>Murphy, Kelly, O’Sullivan, Walsh, Smith, O’Brien, Byrne, Ryan, O’Connor, O’Neill, O’Reilly, Doyle, McCarthy, Gallagher, O’Doherty, Kennedy, Lynch, Murray, Quinn, Moore, McLoughlin, O’Carroll, Connolly, Daly, O’Connell, Wilson, Dunne, Brennan, Burke, Collins, Campbell, Clarke, Johnston, Hughes, O’Farrell, Fitzgerald, Brown, Martin, Maguire, Nolan, Flynn, Thompson, O’Callaghan, O’Donnell, Duffy, O’Mahony, Boyle, Healy, O’Shea, White, Sweeney, Hayes, Kavanagh, Power, McGrath, Moran, Brady, Stewart, Casey, Foley, Fitzpatrick, O’Leary, McDonnell, MacMahon, Donnelly, Regan, Donovan, Burns, Flanagan, Mullan, Barry, Kane, Robinson, Cunningham, Griffin, Kenny, Sheehan, Ward, Whelan, Lyons, Reid, Graham, Higgins, Cullen, Keane, King, Maher, MacKenna, Bell, Scott, Hogan, O’Keeffe, Magee, MacNamara, MacDonald, MacDermott, Molony, O’Rourke, Buckley, O’Dwyer</p>
      </article>








      share|improve this answer


























        0












        0








        0








        Alternation | for each character



        Either the character OR the character followed by an apostrophe





        1. split() the keyword (ex. obrien) into an array of characters:



          var searchLetters = keyword.split('')

          // ['o','b','r','i','e','n']



        2. map() each character into a regex string that will accept either the ${literal match} OR| the ${literal match} followed by a single smart quote: [’ or a single straight quote: ']:



          var regexStrings = searchLetters.map(function(character) {
          return `(${character}|${character}['’])`;
          });

          // [`(${o}|${o}['’])`,`(${b}|${b}['’])`,`(${r}|${r}['’])`...]



        3. Next, join() the new array of regex strings into a single regex string and use it in a RegExp Object:



          var singleRegex = regexStrings.join('');
          var regexObject = new RegExp(`(${singleRegex})`, `gi`);



        4. That RegExp Object will be used to wrap whatever matches with a <mark> tag:



          var hits = targetContent.innerHTML.replace(regexObject, `<mark>$1</mark>`);





        Demo






        document.getElementById('search').addEventListener('change', function(e) {
        highlight(this.value, '#content');
        });

        function highlight(keyword, selector) {
        var node = document.querySelector(selector);
        var html = node.innerHTML;
        var clean = html.replace(/(<mark>|</mark>)/, '');
        var escaped = keyword.replace(/[.*+?^${}()|[]\]/gi, '\$&');
        var letters = escaped.split('').map(function(letter) {
        return `(${letter}|${letter}['’])`;
        });
        var string = letters.join('');
        var regex = new RegExp(`(${string})`, `gi`);
        var hits = clean.replace(regex, `<mark>$1</mark>`);
        node.innerHTML = hits;
        }

        <input id='search' type='search'><input type='button' value='search'>

        <article id='content'>
        <p>Murphy, Kelly, O’Sullivan, Walsh, Smith, O’Brien, Byrne, Ryan, O’Connor, O’Neill, O’Reilly, Doyle, McCarthy, Gallagher, O’Doherty, Kennedy, Lynch, Murray, Quinn, Moore, McLoughlin, O’Carroll, Connolly, Daly, O’Connell, Wilson, Dunne, Brennan, Burke, Collins, Campbell, Clarke, Johnston, Hughes, O’Farrell, Fitzgerald, Brown, Martin, Maguire, Nolan, Flynn, Thompson, O’Callaghan, O’Donnell, Duffy, O’Mahony, Boyle, Healy, O’Shea, White, Sweeney, Hayes, Kavanagh, Power, McGrath, Moran, Brady, Stewart, Casey, Foley, Fitzpatrick, O’Leary, McDonnell, MacMahon, Donnelly, Regan, Donovan, Burns, Flanagan, Mullan, Barry, Kane, Robinson, Cunningham, Griffin, Kenny, Sheehan, Ward, Whelan, Lyons, Reid, Graham, Higgins, Cullen, Keane, King, Maher, MacKenna, Bell, Scott, Hogan, O’Keeffe, Magee, MacNamara, MacDonald, MacDermott, Molony, O’Rourke, Buckley, O’Dwyer</p>
        </article>








        share|improve this answer














        Alternation | for each character



        Either the character OR the character followed by an apostrophe





        1. split() the keyword (ex. obrien) into an array of characters:



          var searchLetters = keyword.split('')

          // ['o','b','r','i','e','n']



        2. map() each character into a regex string that will accept either the ${literal match} OR| the ${literal match} followed by a single smart quote: [’ or a single straight quote: ']:



          var regexStrings = searchLetters.map(function(character) {
          return `(${character}|${character}['’])`;
          });

          // [`(${o}|${o}['’])`,`(${b}|${b}['’])`,`(${r}|${r}['’])`...]



        3. Next, join() the new array of regex strings into a single regex string and use it in a RegExp Object:



          var singleRegex = regexStrings.join('');
          var regexObject = new RegExp(`(${singleRegex})`, `gi`);



        4. That RegExp Object will be used to wrap whatever matches with a <mark> tag:



          var hits = targetContent.innerHTML.replace(regexObject, `<mark>$1</mark>`);





        Demo






        document.getElementById('search').addEventListener('change', function(e) {
        highlight(this.value, '#content');
        });

        function highlight(keyword, selector) {
        var node = document.querySelector(selector);
        var html = node.innerHTML;
        var clean = html.replace(/(<mark>|</mark>)/, '');
        var escaped = keyword.replace(/[.*+?^${}()|[]\]/gi, '\$&');
        var letters = escaped.split('').map(function(letter) {
        return `(${letter}|${letter}['’])`;
        });
        var string = letters.join('');
        var regex = new RegExp(`(${string})`, `gi`);
        var hits = clean.replace(regex, `<mark>$1</mark>`);
        node.innerHTML = hits;
        }

        <input id='search' type='search'><input type='button' value='search'>

        <article id='content'>
        <p>Murphy, Kelly, O’Sullivan, Walsh, Smith, O’Brien, Byrne, Ryan, O’Connor, O’Neill, O’Reilly, Doyle, McCarthy, Gallagher, O’Doherty, Kennedy, Lynch, Murray, Quinn, Moore, McLoughlin, O’Carroll, Connolly, Daly, O’Connell, Wilson, Dunne, Brennan, Burke, Collins, Campbell, Clarke, Johnston, Hughes, O’Farrell, Fitzgerald, Brown, Martin, Maguire, Nolan, Flynn, Thompson, O’Callaghan, O’Donnell, Duffy, O’Mahony, Boyle, Healy, O’Shea, White, Sweeney, Hayes, Kavanagh, Power, McGrath, Moran, Brady, Stewart, Casey, Foley, Fitzpatrick, O’Leary, McDonnell, MacMahon, Donnelly, Regan, Donovan, Burns, Flanagan, Mullan, Barry, Kane, Robinson, Cunningham, Griffin, Kenny, Sheehan, Ward, Whelan, Lyons, Reid, Graham, Higgins, Cullen, Keane, King, Maher, MacKenna, Bell, Scott, Hogan, O’Keeffe, Magee, MacNamara, MacDonald, MacDermott, Molony, O’Rourke, Buckley, O’Dwyer</p>
        </article>








        document.getElementById('search').addEventListener('change', function(e) {
        highlight(this.value, '#content');
        });

        function highlight(keyword, selector) {
        var node = document.querySelector(selector);
        var html = node.innerHTML;
        var clean = html.replace(/(<mark>|</mark>)/, '');
        var escaped = keyword.replace(/[.*+?^${}()|[]\]/gi, '\$&');
        var letters = escaped.split('').map(function(letter) {
        return `(${letter}|${letter}['’])`;
        });
        var string = letters.join('');
        var regex = new RegExp(`(${string})`, `gi`);
        var hits = clean.replace(regex, `<mark>$1</mark>`);
        node.innerHTML = hits;
        }

        <input id='search' type='search'><input type='button' value='search'>

        <article id='content'>
        <p>Murphy, Kelly, O’Sullivan, Walsh, Smith, O’Brien, Byrne, Ryan, O’Connor, O’Neill, O’Reilly, Doyle, McCarthy, Gallagher, O’Doherty, Kennedy, Lynch, Murray, Quinn, Moore, McLoughlin, O’Carroll, Connolly, Daly, O’Connell, Wilson, Dunne, Brennan, Burke, Collins, Campbell, Clarke, Johnston, Hughes, O’Farrell, Fitzgerald, Brown, Martin, Maguire, Nolan, Flynn, Thompson, O’Callaghan, O’Donnell, Duffy, O’Mahony, Boyle, Healy, O’Shea, White, Sweeney, Hayes, Kavanagh, Power, McGrath, Moran, Brady, Stewart, Casey, Foley, Fitzpatrick, O’Leary, McDonnell, MacMahon, Donnelly, Regan, Donovan, Burns, Flanagan, Mullan, Barry, Kane, Robinson, Cunningham, Griffin, Kenny, Sheehan, Ward, Whelan, Lyons, Reid, Graham, Higgins, Cullen, Keane, King, Maher, MacKenna, Bell, Scott, Hogan, O’Keeffe, Magee, MacNamara, MacDonald, MacDermott, Molony, O’Rourke, Buckley, O’Dwyer</p>
        </article>





        document.getElementById('search').addEventListener('change', function(e) {
        highlight(this.value, '#content');
        });

        function highlight(keyword, selector) {
        var node = document.querySelector(selector);
        var html = node.innerHTML;
        var clean = html.replace(/(<mark>|</mark>)/, '');
        var escaped = keyword.replace(/[.*+?^${}()|[]\]/gi, '\$&');
        var letters = escaped.split('').map(function(letter) {
        return `(${letter}|${letter}['’])`;
        });
        var string = letters.join('');
        var regex = new RegExp(`(${string})`, `gi`);
        var hits = clean.replace(regex, `<mark>$1</mark>`);
        node.innerHTML = hits;
        }

        <input id='search' type='search'><input type='button' value='search'>

        <article id='content'>
        <p>Murphy, Kelly, O’Sullivan, Walsh, Smith, O’Brien, Byrne, Ryan, O’Connor, O’Neill, O’Reilly, Doyle, McCarthy, Gallagher, O’Doherty, Kennedy, Lynch, Murray, Quinn, Moore, McLoughlin, O’Carroll, Connolly, Daly, O’Connell, Wilson, Dunne, Brennan, Burke, Collins, Campbell, Clarke, Johnston, Hughes, O’Farrell, Fitzgerald, Brown, Martin, Maguire, Nolan, Flynn, Thompson, O’Callaghan, O’Donnell, Duffy, O’Mahony, Boyle, Healy, O’Shea, White, Sweeney, Hayes, Kavanagh, Power, McGrath, Moran, Brady, Stewart, Casey, Foley, Fitzpatrick, O’Leary, McDonnell, MacMahon, Donnelly, Regan, Donovan, Burns, Flanagan, Mullan, Barry, Kane, Robinson, Cunningham, Griffin, Kenny, Sheehan, Ward, Whelan, Lyons, Reid, Graham, Higgins, Cullen, Keane, King, Maher, MacKenna, Bell, Scott, Hogan, O’Keeffe, Magee, MacNamara, MacDonald, MacDermott, Molony, O’Rourke, Buckley, O’Dwyer</p>
        </article>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 2 at 13:43









        zer00nezer00ne

        24.9k32545




        24.9k32545
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54002974%2fregex-to-match-string-with-or-without-apostrophe%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

            Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

            A Topological Invariant for $pi_3(U(n))$