regular expression :inserting * make it computable - javascript

I have a regular expression as
ysin(yx)
i need to insert * as y*sin(y*x)
suppose my equation is yxsin(y) i need to get output as y*x*sin(y)
i tried with this code
function addStars(str) {
return str.replace(/(\))([A-Za-z])/g,function(str, gr1, gr2) { return gr1 + "*" + gr2 }).replace(/x([A-Za-wy-z])/g,function(str, gr1) { return "x*" + gr1 });
}
var t=addStars("ysin(yx)");
alert(t);
what is wrong with this code.

I suggest using regular back-references in this case since you are not analyzing or manipulating the capture groups. The problem is that you are trying to match some letter after a ) with /(\))([A-Za-z])/g - and you do not have any text after ) in your example string ysin(yx).
Here is a possible fix where I combined the x and y into a character class and set a capture group to be able to restore them in the result:
function addStars(str) {
return str.replace(/([xy])([A-Za-xz])/g,"$1*$2");
// | | ^
// ----------------------|
}
var t=addStars("ysin(yx)");
document.write(t + "<br/>");
var t=addStars("yxsin(y)");
document.write(t);

I've generalized the approch using a function list as an anchor and splitting the variables list. The regex is case insensitive and accepts any letter [a-z] as variables prior and as arguments of the function. The trigonometric function list is (asin|acos|atan|sin|cos|tan) (can be expanded as well, only remember to put the longest function names first!).
Check if can be useful:
function addStars(str) {
return str.replace(/([a-z]*?)(asin|acos|atan|sin|cos|tan)\(([^\)]*)\)/i, function(str, vars, funcName, args) {
return vars.split('').join('*') + '*' + funcName + '(' + args.split('').join('*')+')';});
}
var t=addStars("ysin(yx)");
document.write(t + "<br/>");
var t=addStars("yxsin(y)");
document.write(t + "<br/>");
var t=addStars("ycos(abyxz)");
document.write(t + "<br/>");
var t=addStars("yxatan(yxz)");
document.write(t + "<br/>");

Related

Change data inside string with box brackets

I have a string
garments[0][1]; // The 0 and 1 can be other numbers
I need to replace the data inside the second and the third box brackets.
[0] and [1]
So that it can be
garments[4][6]
Please let me know your suggestions when you get a chance, thank you.
You can try that:
var string = 'garments[' + 4 + '][' + 6 + ']'; //in your onClick function
//To increment dynamically:
var string = 'garments[' + i + '][' + j + ']'; //i and j being variables incrementing in your loops/treatments
Update to address comments:
If you want to break "garnments[0][1]" into "garnments",0 and 1 you can do the following:
var string = "garnments[0][1]";
string = string.split('['); //string = [["garnments"],["0]"],["1]"]]
string[1].replace(']','');
string[2].replace(']',''); //string = [["garnments"],["0"],["1"]]
You can then change values and rebuild your string for further use.
It is a bit brutal though. You can use RegExp as showed by #Diego
You can use String.prototype.replace()
'garments[0][1]'.replace('[0]','[4]').replace('[1]','[6]')
For any possible string with ***[m][n] format:
Function SetNewValues(testString, n, m)
{
var keyWordLengh = testString.indexOf("[");
return testString.substring(0,keyWordLengh) + "[" + n.toString() + "][" + m.toString() + "]";
}
Where:
testString is entire string to work on, like "something[342][345]"
n,m are values to be put inside brackets :)
This would be my approach.
var string = "['foobar'][2][12]";
var match =
/\[([^\]]+)\](?:\[(\d+)\])(?:\[(\d+)\])/g
.exec(string);
console.log(match);

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>';
}
);

check if string is equal to a word and a number

I have an object that contains a string as a property. I want to check that this property is not equal to some word, followed by a space and a number. For instance, something like this:
var TheWordToCheck = "SomeWord";
if (TheObject['SomeProperty'] !== (TheWordToCheck + ' ' + 2)) {...}
if (TheObject['SomeProperty'] !== (TheWordToCheck + ' ' + 3)) {...}
In this example, the code checks for only "SomeWord 2" and "SomeWord 3". How can I simplify this where it checks any numbers?
Thanks.
You could use a regex and the match() method (untested)
var reg = new RegExp("^"+TheWordToCheck+"\\s\\d$")
if (!TheObject['SomeProperty'].match(reg) {...
FIDDLE
depends on the range of numbers you need to check, if it is static or is less than a maximum value, you can use a loop and append the loop variable with the string and check
for (var i=0;i<maxNumber;i++)
{
if (TheObject['SomeProperty'] !== (TheWordToCheck + ' ' + i)) {...
break;
}
}
or you can use regex as suggested in the comments
You can use a regular expression to check this:
var TheWordToCheck = "SomeWord";
var TheObject = {
"SomeProperty": "SomeWord 100"
};
var pattern = new RegExp(TheWordToCheck + ' \\d', 'g');
if (TheObject['SomeProperty'].match(pattern) != null) { ... }
Note that you have to do the backslashes twice in order to make sure that the first one is escaped in the pattern. You should also use the RegEx constructor in order to be able to use a variable in your pattern.

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')
);

Javascript regular expression - matching multiple occurrences

I'm a little stuck on a problem here.
I'm trying to match multiple occurrences of a regular expression in a string, but I don't get all occurrences:
Sample:
s = new RegExp(';' + y[p][0] + '_' + y[p][1] + '_' + y[p][2] + '_([0-9]*);', 'g');
e = null;
e = s.exec(grArr);
while (e != null) {
alert(e[0]+'-'+e[1]+'-'+e[2]); //debugging output
r = r + e[0]; //adding results to output var
e = s.exec(grArr);
}
Sample variables:
//to be searched:
var grArr=';0_0_709711498101583267971121121179999105110111_11994876;0_0_709711498101583267971121121179999105110111_11994877;0_0_709711498101583267971121121179999105110111_11994878;0_0_709711498101583267971121121179999105110111_11994879;0_0_709711498101583268117110107101108103114252110_11994872;0_0_709711498101583268117110107101108103114252110_11994873;0_0_709711498101583268117110107101108103114252110_11994874;0_0_709711498101583268117110107101108103114252110_11994875;0_0_7097114981015832839910411997114122_11994868;0_0_7097114981015832839910411997114122_11994869;0_0_7097114981015832839910411997114122_11994870;0_0_7097114981015832839910411997114122_11994871;0_1_71114246115115101583276_11994870;0_1_71114246115115101583276_11994874;0_1_71114246115115101583276_11994878;0_1_71114246115115101583277_11994869;0_1_71114246115115101583277_11994873;0_1_71114246115115101583277_11994877;0_1_71114246115115101583283_11994868;0_1_71114246115115101583283_11994872;0_1_71114246115115101583283_11994876;0_1_7111424611511510158328876_11994871;0_1_7111424611511510158328876_11994875;0_1_7111424611511510158328876_11994879;'
//search Pattern:
y[0][0]='0';
y[0][1]='1';
y[0][2]='71114246115115101583283';
This results in 2 occurrences - not 3 as it should be.
The problem is that you're using the semicolon twice: Once at the start of the regex, once at the end.
Since in your example the three "matches" directly follow each other, the second occurrence is not found because its preceding semicolon has already been used in the previous match.
Solution: Use word boundaries ('\\b') instead of ';' in your regex.

Categories

Resources