Javascript regex conditional statement when two of same character detected in string - javascript

I am trying to find a regular expression that detects when a string has two periods. When this condition has been met, it deletes all the characters up to (and including) the first period.
string:
"abc.def.ghi"
abc. would be removed, and we have:
"def.ghi"
I've recently learned I can't use conditionals in javascript regex. Is there a solution in regular javascript?
Regex code I have so far
/\.[^.]*\.?/

^[^.]*\.(?=[^.]*\.)
Try this.Replace by empty string.See demo.
https://regex101.com/r/sH8aR8/36
var re = /^[^.]*\.(?=[^.]*\.)/;
var str = 'abc.def.ghi\n\n';
var subst = '';
var result = str.replace(re, subst);

Try this:
str = "abc.def.ghi"
newStr = str.replace(/^[^.]*\.(.*?\.)/, '$1') // def.ghi
Demo

Related

Matching patterns not within a set of opening and closing characters e.g {}, ()

I have this string pattern below
str = "nums#1#2#3{#4}#5"
Its there a way I can match all the #\d+ patterns excluding the ones within the curly braces.
I am currently achieving the desired result by replace the curly braces and everything withing them with an empty string before matching.
str = str.replace(/\{[^}]*\}/g, '');
match = str.match(/#\d+/g);
Its there a way to do this in javascript regular expression without the first replacement?
Assuming { and } are balanced, you can use this negative lookahead to match numbers not within {...}:
var str = "nums#1#2#3{#4}#5";
var arr = str.match(/#\d+(?![^{]*})/g)
console.log(arr)
//=> ["#1", "#2", "#3", "#5"]
(?![^{]*} is a negative lookahead that asserts after a number we don't have a } ahead before matching a {
The way is to capture all that you don't want before, example:
var result = txt.replace(/((?:{[^}]*}|[^#{]|#(?!\d))*)(#\d+)/g, '$1 number:$2 ');
Yes, use this one : (?!{)#\d(?!})
Demo
var str = "nums#1#2#3{#4}#5";
var result=str.match(/#\d+(?!})/g);
console.log(result);
you can write like this too.

Regular Expression to replace part of a string

I need to replace part of a string, it's dynamically generated so I'm never going to know what the string is.
Here's an example "session12_2" I need to replace the 2 at the end with a variable. The "session" text will always be the same but the number will change.
I've tried a standard replace but that didn't work (I didn't think it would).
Here's what I tried:
col1 = col1.replace('_'+oldnumber+'"', '_'+rowparts[2]+'"');
Edit: I'm looking for a reg ex that will replace '_'+oldnumber when it's found as part of a string.
If you will always have the "_" (underscore) as a divider you can do this:
str = str.split("_")[0]+"_"+rowparts[x];
This way you split the string using the underscore and then complete it with what you like, no regex needed.
var re = /session(\d+)_(\d+)/;
var str = 'session12_2';
var subst = 'session$1_'+rowparts[2];
var result = str.replace(re, subst);
Test: https://regex101.com/r/sH8gK8/1

JavaScript - strip everything before and including a character

I am relatively new to RegEx and am trying to achieve something which I think may be quite simple for someone more experienced than I.
I would like to construct a snippet in JavaScript which will take an input and strip anything before and including a specific character - in this case, an underscore.
Thus 0_test, 1_anotherTest, 2_someOtherTest would become test, anotherTest and someOtherTest, respectively.
Thanks in advance!
You can use the following regex (which can only be great if your special character is not known, see Alex's solution for just _):
^[^_]*_
Explanation:
^ - Beginning of a string
[^_]* - Any number of characters other than _
_ - Underscore
And replace with empty string.
var re = /^[^_]*_/;
var str = '1_anotherTest';
var subst = '';
document.getElementById("res").innerHTML = result = str.replace(re, subst);
<div id="res"/>
If you have to match before a digit, and you do not know which digit it can be, then the regex way is better (with the /^[^0-9]*[0-9]/ or /^\D*\d/ regex).
Simply read from its position to the end:
var str = "2_someOtherTest";
var res = str.substr(str.indexOf('_') + 1);

JavaScript: Replacing characters on both sides of a string

What I want to do is to match characters enclosed by ^^ and replace those ^^ while maintaining the string. In other words, turning this:
^^This is a test^^ this is ^^another test^^
into this:
<sc>This is a test</sc> this is <sc>another test</sc>
I got the regex to match them:
\^{2}[^^]+\^{2}
But I'm stuck there. I'm not sure what to do with the other .replace parameter:
.replace(/\^{2}[^^]+\^{2}/g, WHAT_TO_ADD_HERE?)
Any ideas?
You can use replace with regex and grouping like
var text = '^^This is a test^^ this is ^^another test^^'.replace(/\^\^(.*?)\^\^/g, '<sc>$1</sc>')
Here is a piece of code you can use:
var re = /(\^{2})([^^]+)(\^{2})/g;
var str = '^^This is a test^^ this is ^^another test^^\n\n<sc>This is a test</sc> this is <sc>another test</sc>';
var subst = '<sc>$2</sc>';
var result = str.replace(re, subst);
This is just an enhancement of your regex pattern where I added capturing groups. To improve performance and ensure you will be capturing all symbols between the ^^, you can use only one capturing group and . symbol with non-greedy quantificator:
var re = /\^{2}(.+?)\^{2}/g;
Have a look at the example.
In this case you need to use the group index to wrap the content.
var content = "^^This is a test^^ this is ^^another test^^";
content.replace(/\^{2}(.*?)\^{2}/g, '<sc>$1</sc>');
The (.*?) will help you to group the content and in your replace statement use $1 where 1 is the index of group.

Regex Replace failing, and I can't catch the reason?

I use this regex patter with .match() and it works as expected. However, trying to make it work with .replace() appears to be failing, and I can't catch the reason. Maybe I need some new eyes..
(function(){
var testRegex = /^\/Monkey\/tooth\d+\/$/g;
var testStr = '/Monkey/tooth8/';
var testMatch = testStr.match(testRegex,'');
var newString = testStr.replace(testRegex,'');
alert(newString);
if(nullCheck(testMatch) == false){alert('false');}else{alert('true');}
})()
I would expect the alert to alert an empty box but it just alerts the the same thing as testStr. What am I missing from this, I ultimately want to get rid of string in the event it exists. Example output
/Monkey/Tooth10/Hello/World => Hello/World
/Monkey/Tooth10/GoodBye/World => GoodBye/World
Remove ^ and $ to avoid whole string match that assert position at start and end of the string respectively.
You can try
\/Monkey\/tooth\d+\/
OR just remove $
^\/Monkey\/tooth\d+\/
Online demo
Sample code: (use i modifier for ignore-case match)
var re = /\/Monkey\/tooth\d+\//gi;
var str = '/Monkey/Tooth10/Hello/World';
var subst = '';
var result = str.replace(re, subst);
var matchedString = str.match(re);
JavaScript String match() Method
The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object.
Note: If the regular expression does not include the g modifier (to perform a global search), the match() method will return only the first match in the string.
This method returns null if no match is found.
Remove quotes from your regex. So instead of var testRegex = '/^\/Monkey\/tooth\d+\/$/g'; use:
var testRegex = /^\/Monkey\/tooth\d+\/$/g;
In Javascript regex literal is not quoted OR else RegExp object is used.

Categories