M
M
Muranx2020-04-14 10:25:01
JavaScript
Muranx, 2020-04-14 10:25:01

How to make case-sensitive substitutions in a string?

<input class="input" type="text" placeholder="enter regExp here">
<p class="resultParagraph">"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>

let input = document.querySelector('.input');
let p = document.querySelector('.resultParagraph');
let startParagraph = p.innerHTML;

setInterval(()=>{ // просто функция чтобы параграф возвращался к стартовому значению
  if(!input.value)
    p.innerHTML = startParagraph;
}, 1000);


input.addEventListener('keypress', (e)=>{
  if(e.keyCode === 13){
    let res = new RegExp(input.value, 'gmi');
    let m = p.innerHTML.match(res);
     	p.innerHTML = p.innerHTML.replace(res, '<span style="background: red;">'+m[0]+'</span>'); // ! ! !
  }
});

I need that when you enter a inputregular expression in the field, it is in the text and painted in (well, for example) in red. Everything would be fine, but the implementation of this task is of interest without m[0], because for example, if the regular expression takes into account the presence of a flag i(and it takes into account for me), then it turns out that I replace with this m[0]even those matches found in the text, which, for example, began with a capital letter, which of course I don’t need, I just need the found matches to be tinted , while not changing the case. Please suggest an implementation option, in which if, for example, I enter into the input atin the text, all substrings 'at' will not be replaced by 'At'. m[0]in this case equals At.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-04-14
@Muranx

replace can take a function that receives the found substring and should return the replacement:

p.innerHTML.replace(res, m => `<span style="background: red;">${m}</span>`)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question