Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140190

Non-capturing group matching whitespace boundaries in JavaScript regex

$
0
0

I have this function that finds whole words and should replace them. It identifies spaces but should not replace them, ie, not capture them.

function asd (sentence, word) {
     str = sentence.replace(new RegExp('(?:^|\\s)' + word + '(?:$|\\s)'), "*****");
     return str;
};

Then I have the following strings:

var sentence = "ich mag Äpfel";
var word = "Äpfel";

The result should be something like:

"ich mag *****"

and NOT:

"ich mag*****"

I'm getting the latter.

How can I make it so that it identifies the space but ignores it when replacing the word?

At first this may seem like a duplicate but I did not find an answer to this question, that's why I'm asking it.

Thank you


Viewing all articles
Browse latest Browse all 140190


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>