RegExp to replace exact OR similar word JS - javascript

I'm struggling with an Regex to replace the name of a variable inside a string...
I need to put certain variable name outside quotes, and, if that variable have a qualifier (like a property or method), this qualifier need to be outside quotes in the final string, too.
So, given this example:
cExp = new RegExp('oErro', 'g');
cMsg = "Error ocurred: oErro; please try again";
cMsg.replace(cExp, '\' + oErro + \'')
the output is exactly what I expect:
'Error ocurred: ' + oErro + '; please try again'
I search how to include any words after the variable name, and ended up with this piece of code:
cExp = new RegExp('oErro(\.[^\ |^\;|^\,|^\)|^\}]*)', 'g');
cMsg = "Error ocurred: oErro.message; please try again";
cMsg.replace(cExp, '\' + oErro$1 + \'')
and the result is exactly what I expected to see:
'Error ocurred: ' + oErro.message + '; please try again'
So far, so good.
But, if I mix variable name with variable.qualifier, things start to get messy:
cExp = new RegExp('oErro(\.[^\ |^\;|^\,|^\)|^\}]*)', 'g');
cMsg = "Error ocurred: oErro.message (complete message: oErro)";
cMsg.replace(cExp, '\' + oErro$1 + \'')
I GET this output
'Error ocurred: ' + oErro.message + ' (complete message: ' + oErro) + ''
while I EXPECTED this output (note the parenthesis INSIDE the quotes)
'Error ocurred: ' + oErro.message + ' (complete message: ' + oErro + ')'
In other words, every time "oErro" is used without a qualifier, the expression gets the next word and join with oErro, outside the enclosing quotes.
Certainly I'm doing something wrong, but I'm not very familiar with RegExp and maybe not searching with correct terms to get appropriate help.
What I need is an expression that works for both scenarios (removing the word "oErro" or the syntax "oErro.something" from quotes in the final string)...
Thanks in advance and sorry for the poor english, I try to put some examples but feel free to ask if you need more details on what I need to achieve.

You may use
cExp=/oErro(?:\.[^\s;,)}]+)?/g
// Or, if the chars after `.` can only only be letters/digits/underscore
cExp = /oErro(?:\.\w+)?/g
Then, you would need to use
cMsg.replace(cExp, '\' + $& + \'')
where $& is the backreference to the whole match value.
Pattern details
oErro - a literal string
(?:\.\w+)? - an optional (due to ? at the end) non-capturing group that matches 1 or 0 occurrences of
\. - a dot
-\w+ - 1+ letters/digits/underscores
[^\s;,)}]+ - 1 or more chars other than whitespace, ;, ,, ) and }.

I believe your requirement for capturing the property or method name is satisfied by using the \w character in your regex.
With oErro
cMsg = "Error ocurred: oErro; please try again";
cMsg.replace(/(oErro(\.\w+)?)/g, '\' + $1 + \'');
// Output: "Error ocurred: ' + oErro + '; please try again"
With oError.message
cMsg = "Error ocurred: oErro.message (complete message: oErro)";
cMsg.replace(/(oErro(\.\w+)?)/g, '\' + $1 + \'');
// Output: "Error ocurred: ' + oErro.message + ' (complete message: ' + oErro + ')"

Related

indexOf for multiple options

Let say, I get the following using var content = this.innerHTML:
w here </div>
Using indexOf (or other ways), I want to check for the first position that has either "Space", "<" or "&nbsp".
In this case, it will be 1 (after "w").
What I am confused about is how do I check for the very first position that has either one of these three choices? Do I use Do...while to check for individual "options"?
You're probably looking for a Regular Expression (Regex) and the String#search method. Regex is a bit much to learn all at once, but I'll explain this example code.
You can use square brackets to denote a set of characters, so for example [ <] says "match either a space or a less-than sign."
You can use the pipe | to separate possibilities if you want to match one pattern or another, and that's how to account for matching a non-breaking space HTML entity.
var string = 'w here </div>',
index = string.search(/[ <]| /)
console.log(index) //=> 1
You can use a regular expression with alternations (|), which means "match one of these things". That will also tell you what you found, if that's useful:
function check(str) {
var m = / |<| /.exec(str);
if (!m) {
console.log("Not found in '" + str + "'");
return;
}
console.log("'" + m[0] + "' found at index " + m.index + " in '" + str + "'");
}
check("w here </div>");
check("where </div>");
check("where</div>");

Js replace and Regex exclude a word

I have this issue with regex, it doesn't really have friendly syntax for me :(.
Basically I need to match some text and wrap the matched word/letter with a <strong>.
html = html.replace(new RegExp('(' + word + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>';
Now everything works fine except that in some occasion, the previously added <strong> get matched to messing up the html.
So I basically need the html.replace function to ignore any <strong> word during the matching.
I have tried to change new RegExp('(' + word + ')' with new RegExp('(?!\<strong\>)(' + word + ')' but I still have issue.
Ex.
'<strong>Alpinestars</strong> SMX Plus Gore-Tex Boots'.replace(new RegExp('(o)(?!</strong>)', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>';});
returns
"<str<strong>o</strong>ng>Alpinestars</str<strong>o</strong>ng> SMX Plus G<strong>o</strong>re-Tex B<strong>o</strong><strong>o</strong>ts"
You can check if you are not inside an element node with (?![^>]*>) look-ahead:
function escapeRegExp(string){
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
var key = 'o';
var s = '<strong>Alpinestars</strong> SMX Plus Gore-Tex Boots';
var res = s.replace(RegExp(escapeRegExp(key) + '(?![^>]*>)', 'ig'), function (m) {
return '<strong>' + m + '</strong>';});
document.getElementById("t").innerHTML = res.replace(/>/g, ">").replace(/</g, "<");
<div id="t"/>
You also do not need any capturing groups (unless you are using alternations like boots|caps|hats) and do not have to use new with RegExp. I also added an escapeRegExp function from MDN to escape special characters in key if any.
You were close. You just had the order wrong. According to the following mdn page, the x(?!y) means: Matches x only if x is not followed by y.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
So, this seems to work for me:
var word = 'and';
'dogs <strong>and</strong> cats <strong>and</strong>'.replace(
new RegExp('(' + word + ')(?!</strong>)', 'ig'),
function ($1, match) {
return '<strong>' + match + '</strong>';
}
);

Regular expression for replacing string with javascript

I need help in writing regular expression:
part of my string is fixed and another part of its variable.
only if fixed AND variable string exist i need to alter the string other wise no.
Fixed string:example: AA.BBB.COM
Variable string (may or mayn't exist ): US, but if exist it will be always two letter string with any combination of letter.
In below string if I have variable two letter string exist I want to append β€œ.new”
1 ) https://XY**.US**.AA.BBB.COM
Output: https:// XYZ12**.US.NEW**.AA.BBB.COM
2 ) https://XY.UK.AA.BBB.COM
Output: https:// XYZ12.UK.NEW.AA.BBB.COM
3) https://XY.AA.BBB.COM (no variable string so no change)
Output: https:// XY.AA.BBB.COM
Thanks for your help .
Raghav
Something like the following should get you started, there are other methods. Splitting and parsing might suit better depending on your real requirements:
var s = 'https://XY.US.AA.BBB.COM';
var t = 'https://XY.UK.AA.BBB.COM';
var u = 'https://XY.AA.BBB.COM';
var re = /(\.)(UK|US)(\.)/;
alert(
s.replace(re, '$1' + '$2' + '.NEW' + '$3') + '\n' +
t.replace(re, '$1' + '$2' + '.NEW' + '$3') + '\n' +
u.replace(re, '$1' + '$2' + '.NEW' + '$3')
);

Uncaught SyntaxError: Invalid regular expression in Chrome, FF and IE fine

This line of code:
if ( new RegExp("\\b" + arrCategorySort[i]+ "\\b", "g").test(titleText) )
{
catFound = true;
}
works perfect in Firefox (6.0), and in IE (7.0), but not in Chrome (13.0.782.112)
do you have any idea why?
Put a try/catch around your code and display the value that is causing the exception :
try {
if ( new RegExp("\\b" + arrCategorySort[i]+ "\\b", "g").test(titleText) )
catFound = true;
}
catch (e) {
confirm (e + ' : at index ' + i + ', category is "' + arrCategorySort[i] + '"');
}
The problem is that your arrCategorySort[i] as a string contains special characters as far as the RegExp parser is concerned (e.g. {} and []). With your string in place, you're trying to parse regexp
/\bfunction (a,b){var c=b||window,d=[];for(var e=0,f=this.length;e<f;++e){if(!a.call(c,this[e],e,this))continue;d.push(this[e])β€Œβ€‹}return d}\b/
After your (a,b) in the beginning, in {} you have var ... however {} mean repeated pattern and expect to have a number between them (or two numbers). What you really need is to escape all special chars: {}[]|()\,.*+ - by prepending '\' character in front of each of them. (There may be a couple more, escapes me at the moment.)

RegExp function not working with alternation

string=string.replace(RegExp(filter[a]+" | "+filter[a],"g"),filter[a])
For some reason, this isn't affecting both the filter followed by the space and the filter with a space in front. Assuming the filter is ",", it would take the second side and only replace " ," rather than " ," and ", ". The filter is user-specified, so I can't use a normal regular expression (which DOES work) such as string=string.replace(/, | ,/g,filter[a])
Can someone explain to me why it doesn't work and how to make it work?
It works for me:
s = 'abc, def,ghi ,klm'
a = ','
s = s.replace(RegExp(a + " | " + a, "g"), a)
"abc,def,ghi,klm"
Remember that you regular expression won't replace " , " with ",". You could try using this instead:
" ?" + filter[a] + " ?"

Categories

Resources