Regex append characters to a substring - javascript

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"

Related

Javascript regexp replace capturing

I'm trying to use regex in a Nodejs app. I usually use it in Python and it seems to have some differences.
Here is the problem :
I have this string \newcommand{\hello}{#replace} and I want to replace #replace by REPLACED in the second curly bracelets ONLY when I found \hello in the first curly bracelets. So the expected result is : \newcommand{\hello}{REPLACED}
I try this:
r = new RegExp('\\newcommand{\\hello}{(.*?)}');
s = '\\newcommand{\\hello}{#replace}';
s.replace(r, 'REPLACED');
But nothing is replaced... any clue?
r = new RegExp(/\\newcommand{\\hello}{#replace}/);
s = '\\newcommand{\\hello}{#replace}';
let a = s.replace(r, '\\newcommand{\\hello}{REPLACED}');
console.log(a)
Output would be : "\newcommand{\hello}{REPLACED}"
I'm not sure if I understood the question correctly. Is this what you're looking for?
function replaceWith(myReplacement) {
var original = "\\newcommand{\\hello}{#replace}";
var regex = "{\\hello}{#replace}";
return original.replace(regex, `{\\hello}{${myReplacement}}`)
};
console.log(replaceWith("World"));
You don't need regex at all to perform this kind of operation. You can simply use string at first parameter:
s = '\\newcommand{\\hello}{#replace}';
s.replace('#replace', 'REPLACED'); // => "\newcommand{\hello}{REPLACED}"

Check string starting with substring using regex

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.

How To Remove All Text Before a Specific Value in a String

I have the following string, "blahblahhellothere", that I would like to be shortened to "hellothere" using JavaScript and/or JQuery.
I have tried using the following code:
var titletext123 = "blahblah<br>hellothere"
var injuryt3xt = titletext123.substring(titletext123.indexOf("<br>") +1);
Which only returns "br>hellothere".
Does anyone have any code which will get rid of the and all text before it?
Thank you very much. All of your help is appreciated!
Make it
var titletext123 = "blahblah<br>hellothere" var injuryt3xt = titletext123.substring(titletext123.indexOf("<br>") + 4);
So it is +4. Which accounts for all the characters in <br>.
You can use split() and get second element.
var titletext123 = "blahblah<br>hellothere" ;
var injuryt3xt = titletext123.split("<br>")[1];
alert(injuryt3xt);
Using regular expression:
var text = "blahblah<br>hellothere"
var clipped = str.replace(/.+\<br\>/, ""));
Another option (depending on circumstances) might be:
var injuryt3xt = titletext123.split("<br>")[1];
Which would split the string on <br> and return an array with the left-over parts ... the second of which is referred to with the [1]

JavaScript regex matching

I have some variable
var jdbcurl="jdbc:oracle:thin:%2F%2Finnova:1521%3BServiceName%3Dorcl%3BMaxPooledStatements%3D20%3BCatalogOptions%3D0%3BBatchPerformanceWorkaround%3Dtrue"
alert(jdbcurl.match(/:[\d]+/)); //gives me :1521
How can I get jdbc:oracle:thin, innova, 1521 & orcl out of jdbcurl var?
Update
You can experiment here (if needed)
var jdbcurl="jdbc:oracle:thin:%2F%2Finnova:1521%3BServiceName%3Dorcl%3BMaxPooledStatements%3D20%3BCatalogOptions%3D0%3BBatchPerformanceWorkaround%3Dtrue"
var myregex = /([a-z:]+):%2F%2F([a-z]+):(\d+)%3BServiceName%3D([a-z]+)%3BMaxPooledStatements%3D20%3BCatalogOptions%3D0%3BBatchPerformanceWorkaround%3Dtrue/
var matches = myregex.exec(jdbcurl);
// jdbc:oracle:thin is in matches[1], innova is in matches[2], 1521 is in matches[3], and orcl is in matches[4]
you could also try this for better url readability during regexp maintenance if you have to parse several urls:
var jdburl = unescape("jdbc:oracle:thin:%2F%2Finnova:1521%3BServiceName%3Dorcl%3BMaxPooledStatements%3D20%3BCatalogOptions%3D0%3BBatchPerformanceWorkaround%3Dtrue");
var myRegExp = new Regexp('([a-z:]+)://(\\w+):(\\d+);ServiceName=(\\w+);');
var matches = myRegExp.exec(jdburl);
I'd say jdbcurl.split(/(%..)/) would be a start - and then you could check the elements on whether to keep them or split them even further.
Use decodeURIComponent() first, then split on semicolons. Don't make it hard on yourself!

JavaScript indexOf to ignore Case

I am trying to find if an image has in its source name noPic which can be in upper or lower case.
var noPic = largeSrc.indexOf("nopic");
Should I write :
var noPic = largeSrc.toLowerCase().indexOf("nopic");
But this solution doesn't work...
You can use regex with a case-insensitive modifier - admittedly not necessarily as fast as indexOf.
var noPic = largeSrc.search(/nopic/i);
No, there is no case-insensitive way to call that function. Perhaps the reason your second example doesn't work is because you are missing a call to the text() function.
Try this:
var search = "nopic";
var noPic = largeSrc.text().toLowerCase().indexOf(search.toLowerCase());
Note that if the search string is from user input you'll need to escape the special regexp characters.
Here's what it would look like:
var search = getUserInput();
/* case-insensitive search takes around 2 times more than simple indexOf() */
var regex = RegExp(search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "i");
var noPic = testString.search(regex);
See the updated jsperf: http://jsperf.com/regex-vs-tolowercase-then-regex/4
footnote: regexp escaping from https://stackoverflow.com/a/3561711/1333402
Try with:
var lowerCaseLargeSrc = largeSrc.toLowerCase();
var noPic = lowerCaseLargeSrc.indexOf("nopic");
Your code will only work if largeSrc is already a string. You might be getting an input that's an html element instead. So, use jQuery to resolve any potential input element into the text that's inside it. Example:
var noPic = largeSrc.text().toLowerCase().indexOf("nopic");
How about using findIndex instead that way you can do all your toLowerCase() inside the callback. Worked great for me:
// Not Supported in IE 6-11
const arr = ['HELLO', 'WORLD'];
const str = 'world';
const index = arr.findIndex(element => {
return element.toLowerCase() === str.toLowerCase();
});
console.log(index); // 👉️ 1
if (index !== -1) {
// 👉️ string is in the array
}
Credit:
https://bobbyhadz.com/blog/javascript-make-array-indexof-case-insensitive

Categories

Resources