Replacing two separate regular expressions with brackets within one string - javascript

I am trying to replace a string with two fractions "x={2x-21}/{x+12}+{x+3}/{x-5}" with a string
"x=\frac{2x-21}{x+12}+\frac{x+3}{x-5}" (i.e. convert from jqMath to LaTex).
To achieve this, I've written the following code:
var initValue = "(\{.*\}(?=\/))\/(\{.*\})";
var newValue = "\\frac$1$2";
var re = new RegExp (initValue,"g");
var resultString = givenString.replace(re,newValue);
return resultString;
This code seems to work for strings with just one fraction (e.g. "x={2x-21}/{x+12}") but when I try to apply it to the example with two fractions, the result is x=\frac{2x-21}/{x+12}+{x+3}{x-5}. As far as I understand, regex engine captures {2x-21}/{x+12}+{x+3} as the first group and {x-5} as the second group. Is there any way to get the result that I want with regular expressions?
The same question is applicable to other patterns with several non-nested delimiters, for example: "I like coffee (except latte) and tea (including mint tea)". Is it possible to capture both statements in parentheses?
If not, I will probably have to write a function for this (which is ok, but I wanted to make sure this is the right approach).

({[^}]+})\/({[^}]+})
Try this.See demo.Repalce by \\frac$1$2.
http://regex101.com/r/tF5fT5/24

Related

Check if all elements in array are present in a string as words using regular expressions in Javascript

I have used existing Javascript functions that I found online but I need more control and I think regular expressions will allow it using flags to control if case sensitive or not, multiline etc.
var words=['one','two','cat','oranges'];
var string='The cat ate two oranges and one mouse.';
check=string.match(pattern);
pattern=???;
if(check!==null){
//string matches all array elements
}else{
//string does not match all array words
}
what would the pattern be and if it can be constructed using javascript using the array as a source?
***I will need to place the same function on the backend in PHP and so it would be easier just to create a regular expression and use it instead of looping and finding alternatives for this to work in PHP.
***I would love to have as many options including changes, replace, count and regular expressions are meant for this. And on the plus side the speed should be better using regex instead of looping(search the whole text for every element in the array) specially in case of a long array and a long string.
var words=['one','two','cat','oranges'];
let string='The cat ate two oranges and one mouse.';
words=words.map(function(value,index){return '(?=(.)*?\\b('+value+')\\b)'; }).join('');
let pattern=new RegExp(`${words}((.)+)`,'g');
if(string.match(pattern)!==null){
//string matches all elements
}else{
//string does not match all words
}
It will look for the exact word match, and you will have the extra control you wanted using regex flags for case insensitive..
if you want to test it or adjust it you can do it here:
doregex.com
You can use the same regex to make changes within the text using a callback function.
You can create RegExp objects from your strings, this will allow you further control over case sensitivity etc.
For example:
const patterns = [ 'ONE','two','cat','oranges'];
const string = 'The cat ate two oranges and one mouse.';
// Match in a case sensitive way
const result = patterns.every(pattern => new RegExp(pattern, 'i').test(string));
console.log("All patterns match:", result);

How would I go about splitting a string by two brackets with regex?

I have been working with Discord.js and Node to a quick bot to look up something. I need a way to find all the occurrences that appear between two square brackers and store them in an array of strings. For now I'm using string-split() with some regex, but I am unsure of the regex to use.
I have tried using a few different ones, including /[^\[\[]+(?=\]\])/g and \[\[(.*?)\]\] - I dont mind having the actual brackets in the results, I can remove them manually with string.replace().
I am also working on a fallback with the normal string.split() and other string functions, not relying on regex, but I'm still curious about a possible regex version.
The result with the first regex is totally incorrect. For example, if I try "does [[this]] work [at all]?" the output is "[[]]" and "[at all]", when it really shouldn't take the "at all", but it shouls show the "[[this]]".
With the second regex I get somewhat closer, it gives back "this"(correct) and "[at all]" (again, it shouldn't take the "at all").
I don't mind having the brackets in the output, I can remove them manually myself, but I need to find all occurrences that are specifically between two brackets.
Try this regex:
\[\[([^[\]]|(?R))*\]\]
What you are trying to do is called Matching Balanced Constructs. More info at the link.
Upon further testing, unfortunately JS does not support (?R) so this becomes far more difficult. You could use the XRegExp.matchRecursive addon from the XRegExp package.
And your expression \[\[(.*?)\]\] should work. Working example below.
var str = 'does [[this]] work [at all] with another double [[here]]?';
var result = str.match(/\[\[(.*?)\]\]/g);
var newDiv = document.createElement("div");
newDiv.innerHTML = result;
document.body.appendChild(newDiv);
Try my solution
var str = "does [[this]] work [at all]?";
var regexp = /\[([a-z0-9\s]+)\]/ig;
var resultArray = str.match(regexp);
resultArray = resultArray.map((item) => {
return item.replace(/(\[|\])/g, "");
})
console.log(resultArray);

How do I capture a regex greedily based on a different situation?

Currently, I am trying to implement string interpolation for my language.
The string interpolation looks something like this:
let x = " Baby"
let message = "Hello $(x)"
My current regex to capture interpolated expression is:
const regex = /[$][(].*?[)]/g;
However, the regex above works well with non-bracketed expressions, but it does not work properly when the interpolated expression have brackets, for example:
let message = "My number is $(square(1+2))"
// the captured group would be `$(square(1+2)` , which is missing a bracket
I could not use greedy quantifiers. If not it will not work when there is more than one interpolated expression, such as:
let message = "My number is $(x) $(y) $(z)"
// if capture greedily, it would be `$(x) $(y) $(z)`, which is not desired
How do I greedily capture interpolated expressions based on situations?
Note: I'm looking for answer in JavaScript.
You can use template string (or literal string) like this
let x = 1, y = 2, z = 3;
console.log(`Mu number ${x} ${y} ${z}`);
Updated regex what you created, this will allow you to capture the second bracket it is there. Please find the following regex, btw I am not able to understand the third scenario. Test this regex and let me know if it fulfills your reqt. If not then elaborate on the third scenario and I will update my regex.
For scenario 3:
'[$][(].*?[\)]+' will capture '$(x)' '$(y)' '$(z)' differently. Mean to say match individually.
'[$][(].*[\)]+' will capture '$(x) $(y) $(z)' as one string. Whole string.
Please let me know if it works.

Javascript regex expression to replace multiple strings?

I've a string done like this: "http://something.org/dom/My_happy_dog_%28is%29cool!"
How can I remove all the initial domain, the multiple underscore and the percentage stuff?
For now I'm just doing some multiple replace, like
str = str.replace("http://something.org/dom/","");
str = str.replace("_%28"," ");
and go on, but it's really ugly.. any help?
Thanks!
EDIT:
the exact input would be "My happy dog is cool!" so I would like to get rid of the initial address and remove the underscores and percentage and put the spaces in the right place!
The problem is that trying to put a regex on Chrome "something goes wrong". Is it a problem of Chrome or my regex?
I'd suggest:
var str = "http://something.org/dom/My_happy_dog_%28is%29cool!";
str.substring(str.lastIndexOf('/')+1).replace(/(_)|(%\d{2,})/g,' ');
JS Fiddle demo.
The reason I took this approach is that RegEx is fairly expensive, and is often tricky to fine tune to the point where edge-cases become less troublesome; so I opted to use simple string manipulation to reduce the RegEx work.
Effectively the above creates a substring of the given str variable, from the index point of the lastIndexOf('/') (which does exactly what you'd expect) and adding 1 to that so the substring is from the point after the / not before it.
The regex: (_) matches the underscores, the | just serves as an or operator and the (%\d{2,}) serves to match digit characters that occur twice in succession and follow a % sign.
The parentheses surrounding each part of the regex around the |, serve to identify matching groups, which are used to identify what parts should be replaced by the ' ' (single-space) string in the second of the arguments passed to replace().
References:
lastIndexOf().
replace().
substring().
You can use unescape to decode the percentages:
str = unescape("http://something.org/dom/My_happy_dog_%28is%29cool!")
str = str.replace("http://something.org/dom/","");
Maybe you could use a regular expression to pull out what you need, rather than getting rid of what you don't want. What is it you are trying to keep?
You can also chain them together as in:
str.replace("http://something.org/dom/", "").replace("something else", "");
You haven't defined the problem very exactly. To get rid of all stretches of characters ending in %<digit><digit> you'd say
var re = /.*%\d\d/g;
var str = str.replace(re, "");
ok, if you want to replace all that stuff I think that you would need something like this:
/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g
test
var string = "http://something.org/dom/My_happy_dog_%28is%29cool!";
string = string.replace(/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g,"");

Javascript Regex after specific string

I have several Javascript strings (using jQuery). All of them follow the same pattern, starting with 'ajax-', and ending with a name. For instance 'ajax-first', 'ajax-last', 'ajax-email', etc.
How can I make a regex to only grab the string after 'ajax-'?
So instead of 'ajax-email', I want just 'email'.
You don't need RegEx for this. If your prefix is always "ajax-" then you just can do this:
var name = string.substring(5);
Given a comment you made on another user's post, try the following:
var $li = jQuery(this).parents('li').get(0);
var ajaxName = $li.className.match(/(?:^|\s)ajax-(.*?)(?:$|\s)/)[1];
Demo can be found here
Below kept for reference only
var ajaxName = 'ajax-first'.match(/(\w+)$/)[0];
alert(ajaxName);
Use the \w (word) pattern and bind it to the end of the string. This will force a grab of everything past the last hyphen (assuming the value consists of only [upper/lower]case letters, numbers or an underscore).
The non-regex approach could also use the String.split method, coupled with Array.pop.
var parts = 'ajax-first'.split('-');
var ajaxName = parts.pop();
alert(ajaxName);
you can try to replace ajax- with ""
I like the split method #Brad Christie mentions, but I would just do
function getLastPart(str,delimiter) {
return str.split(delimiter)[1];
}
This works if you will always have only two-part strings separated by a hyphen. If you wanted to generalize it for any particular piece of a multiple-hyphenated string, you would need to write a more involved function that included an index, but then you'd have to check for out of bounds errors, etc.

Categories