rurp rurp - 3 years ago 45
Javascript Question

Javascript regex optional character at any position and bordered by specific characters

I need to find and change a given string wherever it occurs within a document. There are two conditions which I can handle separately but can't get to work together.


  1. Words are sometimes broken across lines with
    -\n
    and those should always be matched.

  2. The string should only be matched if it is bordered by a character which is not alphanumeric nor a hyphen.



Suppose I want to wrap the matched text with a
<stuff>
tag. For the first I have the following which feels ugly but works. I insert an optional
-\n
group between each character in every word.

function createMask(term){
var words = term.split(' ');
new_words = [];
for(i=0; i<words.length; i++){
var word = words[i].split('').join('(\\-\\n)?');
new_words.push(word);
}
var mask = new_words.join('\\s'); \\Any space is ok here.
return mask;
}
var doc = 'This is sand, and rand,\nand something else a-\nn-\nd ';
var mask = createMask('and');
var newDoc = doc.replace(RegExp(mask, 'ig'), '<stuff>$&</stuff>');


This matches the last 'and' but also the ones within 'sand' and 'rand'.

For the second I can do the following

function createMask(term){
var mask = '([^a-zA-Z0-9-])(' + term + ')([^a-zA-Z0-9-])';
return mask;
}
var doc = 'This is sand, and rand,\nand something else a-\nn-\nd ';
var mask = createMask('and');
var newDoc = doc.replace(RegExp(mask, 'ig'), '$1<stuff>$2</stuff>$3');


Combining the expressions together works except for the fact that the capture groups are wrong. I tried switching
(\\-\\n)?
to
(?:\\-\\n)
, but then failed to match anything. Any help is much appreciated.

Answer Source

You are mostly wanting a word-boundary \b. You can also shorten your code to this two-line snippet:

var text = 'This is sand, and dand rand,\nand something else a-\nn-\nd dand';
var words = 'and dand'
console.log(text.replace(RegExp('\\b' + words.replace(/\B|(\S)\b/g, '$1(?:-\\n)?').replace(/\s/g, '\\s') + '\\b', 'ig'), '<stuff>$&</stuff>'))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download