Check string starting with substring using regex - javascript

Trying to check if randomString starting with just. (including the dot).
This should give me false but it's not the case:
var randomString = 'justanother.string';
var a = randomString.match('^just\.');
console.log(a);
I probably missed something in the regex argument.

You need to use create a Regular Expression and the use .test() method.
var randomString = 'justanother.string';
var a = /^just\./.test(randomString)
console.log(a);

The answer is simple, you didn't create regex propertly.
'this is not regex'
/this is regex/
new RexExp('this is also regex')
var randomString = 'justanother.string';
var a = randomString.match(/^just\./);
console.log(a);
// I sugest dooing something like this
const startsWithJust = (string) => /^just\./.test(string)

var randomString = 'justanother.string';
var another = 'just.....................';
console.log( randomString.match('^(just[.]).*') );
console.log( another.match('^just[.].*') );

If you wish to keep your lines the same only one change is needed.
var a = randomString.match('^just\\.');
you need to escape the first backslash.

Related

How to use a variable in a match method with regular expression pattern

I want to get an array in JavaScript from a string, cutting it in half.
Example:
// From this:
var myStr = 'cocacola';
// To this:
var myArray = ['coca', 'cola'];
I tried the following method:
var myStr = 'cocacola';
var strHalf = myStr.length / 2;
// This won't work
var myArray = myStr.match(/.{1,strHalf}/g);
// Only this will work fine
var myArray = myStr.match(/.{1,4}/g);
You can do String.slice() to solve this
var myStr = 'cocacola';
let len = myStr.length;
let result = [myStr.slice(0, len/2), myStr.slice(len/2)]
console.log(result);
You'll need to to use the RegExp() constructor and make a string that it understands:
var regexString = "/.{1," + strHalf + "}/g";
var myRegex = new RegExp( regexString );
var myArray = myStr.match( myRegex );
...but be careful doing this; if strHalf is a string containing special characters like / then your RegExp will have weird behaviour.
You can create a non-hardcoded regexp by using the RegExp constructor:
var myArray = myStr.match(new RegExp('/.{1,'+strHalf+'}/g'));
The constructor has no clue that strHalf should be an integer, so make sure you can control that.
This is known to introduce a lot of security issues, please don't use this in production. Regexes are too often used when they shouldn't. If you ever use a regex, do look into other options
There are much better alternatives, but at least it's possible!
You dont need regex for that.
The easiest way is that:
var myStr = 'cocacola';
var strHalf = myStr.length / 2;
var array = [myStr.substr(0, strHalf),myStr.substr(strHalf, myStr.length)];
jsfiddle: https://jsfiddle.net/cudg8qc3/
You can just slice the string and place the first element in the first slot, and the second element in the second slot in the array.
var str_len = myStr.length
var my_array = [myStr.slice(0, str_len/2), myStr.slice(str_len/2, str_len)]

Regex append characters to a substring

My string comes in two flavours-
var a = /aid/f82eb514073124cd10d468b74eee5663?sg=1#/propertyinfo
or
var a = /aid/f82eb514073124cd10d468b74eee5663#/propertyinfo
I want to append the content that comes after aid/ and before ? or # with "-test". In either of the above scenarios the result would be f82eb514073124cd10d468b74eee5663-test
hence
a = /aid/f82eb514073124cd10d468b74eee5663-test#/propertyinfo
or
a = = /aid/f82eb514073124cd10d468b74eee5663-test?sg=1#/propertyinfo
Seems like you're looking for something like this.
Regular expression /\/aid\/[0-9A-F]*/i and replacement expression $0-test.
JavaScript is a little bit different than just plain regular expression antics, so here you go;
var a = "/aid/f82eb514073124cd10d468b74eee5663?sg=1#/propertyinfo";
alert(a.replace(/(\/aid\/[0-9A-F]*)/i, "$1-test"));
given your examples I guess that string after /aid/ is some kind of md5 hash
this should work for you:
'/aid/f82eb514073124cd10d468b74eee5663#/propertyinfo'.replace(new RegExp('/aid/([a-f0-9]{32})'), '$1-test');
if you don't want to be that much specific about length, you can try the following:
'/aid/f82eb514073124cd10d468b74eee5663#/propertyinfo'.replace(new RegExp('/aid/([a-f0-9]+)'), '$1-test');
Simple solution using String.replace function:
var a = '/aid/f82eb514073124cd10d468b74eee5663sg=1#/propertyinfo',
result = a.replace(/aid\/([^?#]+)(?=\?|#)/, "aid/$1-test");
console.log(result); // /aid/f82eb514073124cd10d468b74eee5663-test?sg=1#/propertyinfo
I suggest replacing directly the # or ? so the regex is nice and simple. :)
var a = "/aid/f82eb514073124cd10d468b74eee5663?sg=1#/propertyinfo";
var b = "/aid/f82eb514073124cd10d468b74eee5663#/propertyinfo";
console.log(a.replace(/([\?#])/,"-test$1"));
console.log(b.replace(/([\?#])/,"-test$1"));
var a = '/aid/f82eb514073124cd10d468b74eee5663?sg=1#/propertyinfo';
a.replace(/(\/aid\/.+)(\?sg=1)(#\/propertyinfo)/,function(text,c,d,e){
return c+'-test'+e;
})
//Output: "/aid/f82eb514073124cd10d468b74eee5663-test#/propertyinfo"
a.replace(/(\/aid\/.+)(\?sg=1#\/propertyinfo)/,function(text,c,d){
return c+'-test'+d;
});
//Output: "/aid/f82eb514073124cd10d468b74eee5663-test?sg=1#/propertyinfo"

Pattern match to get string between brackets

I am trying to find whatever string is in between the aggregate() and find(). Below is my code.
var str1 = 'aggregate([{$group:{_id:{state:"$state",city:"$city"},sum:{$sum:"$pop"}}},{$sort:{sum:1}},{$group:{_id:"$_id.state",smallestcity:{$first:"$_id.city"},smallest:{$first:"$sum"},largestcity:{$last:"$_id.city"},largest:{$last:"$sum"}}}])'
var str2 = 'find({awards:{$elemMatch:{award:"Turing Award",year:{$gt:1980}}}}).limit(0)'
var matchPharse = /((.*))/;
var result = str1.match(matchPharse);
console.log(result);
I am getting the result always the whole string instead of
[{$group:{_id:{state:"$state",city:"$city"},sum:{$sum:"$pop"}}},{$sort:{sum:1}},{$group:{_id:"$_id.state",smallestcity:{$first:"$_id.city"},smallest:{$first:"$sum"},largestcity:{$last:"$_id.city"},largest:{$last:"$sum"}}}]
I am searching for something like this
try this pattern instead:
var matchPharse = /((\[.*\]))/;
((\[.*?\]))
You Should use a non greedy expression.
Try the following RegEx:
var matchPharse= /\((.*)\)/g;
Matches any sequence between ().
This is a DEMO.
var str1 = 'aggregate([{$group:{_id:{state:"$state",city:"$city"},sum:{$sum:"$pop"}}},{$sort:{sum:1}},{$group:{_id:"$_id.state",smallestcity:{$first:"$_id.city"},smallest:{$first:"$sum"},largestcity:{$last:"$_id.city"},largest:{$last:"$sum"}}}])'
var str2 = 'find({awards:{$elemMatch:{award:"Turing Award",year:{$gt:1980}}}}).limit(0)'
var matchPharse = /\((.*)\)/;
var result = str1.match(matchPharse);
alert(result);
You just need to escape the outside parentheses. Try:
var matchPharse = /\((.*)\)/;
For just the content inside the parentheses use result[1]

Search through string with Javascript

Say I have a string like this:
jJKld-xxx-JKl122
Using javascript, how can I get on what's in-between the - characters? In others words, all I need to do is put whatever is xxx into a variable.
Thanks
If the string is always in that format, this will work:
var foo = 'jJKld-xxx-JKl122';
var bar = foo.split('-')[1]; // = xxx
just try it with this simple regex
var str = 'jJKld-xxx-JKl122';
var xxx = str.replace( /^[^\-]*-|-[^\-]*$/g, '' );
You can simply use the following regex to get the result
var myString = "jJKld-xxx-JKl122";
var myRegexp = /(?:^|\s*)-(.*?)-(?:^|\s*)/g;
var match = myRegexp.exec(myString);
alert(match[1]);
See the demo here

Quick Problem - Extracting numbers from a string

I need to extract a single variable number from a string. The string always looks like this:
javascript:change(5);
with the variable being 5.
How can I isolate it? Many thanks in advance.
Here is one way, assuming the number is always surrounded by parentheses:
var str = 'javascript:change(5);';
var lastBit = str.split('(')[1];
var num = lastBit.split(')')[0];
Use regular expressions:-
var test = "javascript:change(5);"
var number = new RegExp("\\d+", "g")
var match = test.match(number);
alert(match);
A simple RegExp can solve this one:
var inputString = 'javascript:change(5);';
var results = /javascript:change\((\d+)\)/.exec(inputString);
if (results)
{
alert(results[1]); // 5
}
Using the javascript:change part in the match as well ensures that if the string isn't in the proper format, you wont get a value from the matches.
var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);
if ( result ) {
alert( result[1] )
}

Categories

Resources