Matching _{number} with Regex in javascript - javascript

I am trying the match part of an image src, an example would be:
images/preview_1.jpg
and I want to change _1 to say _6
so I’m trying to match _1
function ClickImgOf(filename, itemid){
var re = new RegExp("(.+)_[0-9])\\.(gif|jpg|jpg|ashx|png)", "g");
return filename.replace(re, "$1_"+itemid+".$2");
}
Is the function I have..
I know that only matches 0-9 but I was just trying to get something to work and even that didn't.
Its fair to say I do not know much about Regex at the moment.

You have an unmatched ) parenthesis there in your pattern. Is that what's throwing you off? Looks okay otherwise. If your problem is being able to match 2-or-more-digit numbers, try [0-9]+.
function ClickImgOf(filename, itemid){
var re = new RegExp("(.+)_([0-9]+)\\.(gif|jpg|jpg|ashx|png)", "g");
return filename.replace(re, "$1_"+itemid+".$3");
}

Try this:
(.+_)[0-9]+(\.(?:gif|jpg|jpg|ashx|png))
Then you can just do:
return filename.replace(re, "$1" + itemid + "$2");
Also, download and install this: http://www.ultrapico.com/ExpressoDownload.htm
It's invaluable when working with regular expressions.

You don't need to build your regex using the regex object, it's both easier and performs better to use a literal.
function ClickImgOf(filename, itemid) {
return filename.replace(/_\d+\.(gif|jpg|jpg|ashx|png)$/g, '_'+itemid+'.$2');
}

Related

How to parse functions names from string using javascript?

I'm looking for a reliable way to get function names from a string. The string values can be something like this:
let str = 'qwe(); asd();zxc()'
//or
let str = 'qwe("foo");asd(1);zxc();'
//etc.
I want to have an array
['qwe', 'asd', 'zxc']
I tried str.split(';') but how do I get rid of parenthesis and anything they can hold? Is there a regexp that will match all symbols on the left of some other symbol?
You can use this simple regex to find function names in .match()
var str = "qwe(); asd();zxc()";
console.log(str.match(/\w+(?=\()/g));
The first case it's fairly simple with regex a simple
[A-Za-z]\w+
would suffice.
on the second case it's a little bit trickier but maybe supressing the match for this
"(.*?)"
maybe a possibility

Javascript RegEx global string search for underscore character(_)

I am horrible with RegEx and I have been using this online tester for some time now and still can not find what I need.
So I have the string "2011_G-20_Cannes_summit". I want to replace all the underscores (_) with spaces.
So I want something like this:
var str = "2011_G-20_Cannes_summit";
str.replace(/_/g," "); or str.replace(/\_/g);
Though neither is working...
What am I missing?
That works fine. The replace method doesn't modify the existing string, it creates a new one. This will do what you want:
var str = "2011_G-20_Cannes_summit";
str = str.replace(/_/g," ");

Passing regex modifier options to RegExp object

I am trying to create something similar to this:
var regexp_loc = /e/i;
except I want the regexp to be dependent on a string, so I tried to use new RegExp but I couldn't get what i wanted.
Basically I want the e in the above regexp to be a string variable but I fail with the syntax.
I tried something like this:
var keyword = "something";
var test_regexp = new RegExp("/" + keyword + "/i");
Basically I want to search for a sub string in a larger string then replace the string with some other string, case insensitive.
regards,
alexander
You need to pass the second parameter:
var r = new RegExp(keyword, "i");
You will also need to escape any special characters in the string to prevent regex injection attacks.
You should also remember to watch out for escape characters within a string...
For example if you wished to detect for a single number \d{1} and you did this...
var pattern = "\d{1}";
var re = new RegExp(pattern);
re.exec("1"); // fail! :(
that would fail as the initial \ is an escape character, you would need to "escape the escape", like so...
var pattern = "\\d{1}" // <-- spot the extra '\'
var re = new RegExp(pattern);
re.exec("1"); // success! :D
When using the RegExp constructor, you don't need the slashes like you do when using a regexp literal. So:
new RegExp(keyword, "i");
Note that you pass in the flags in the second parameter. See here for more info.
Want to share an example here:
I want to replace a string like: hi[var1][var2] to hi[newVar][var2].
and var1 are dynamic generated in the page.
so I had to use:
var regex = new RegExp("\\\\["+var1+"\\\\]",'ig');
mystring.replace(regex,'[newVar]');
This works pretty good to me. in case anyone need this like me.
The reason I have to go with [] is var1 might be a very easy pattern itself, adding the [] would be much accurate.
var keyword = "something";
var test_regexp = new RegExp(something,"i");
You need to convert RegExp, you actually can create a simple function to do it for you:
function toReg(str) {
if(!str || typeof str !== "string") {
return;
}
return new RegExp(str, "i");
}
and call it like:
toReg("something")

Javascript regex with deep objects replacement issue

Hey all, having an issue doing string replacement for template engine code I am writing. If my tokens are 1 level deep everything works fine. Example {someProperty}. But if I try searching for a nested object it never does the replace. Example {myobj.deep.test}. I've attached the code I am playing around with. Thanks for the help!
function replaceStuff(content, fieldName, fieldValue) {
var regexstr = "{" + fieldName + "}";
console.log("regexstr: ", regexstr);
//var regex = new RegExp("{myobj\.deep\.test}", "g"); //this works as expected
var regex = new RegExp(regexstr, "g"); //this doesn't
return content.replace(regex, fieldValue);
}
replaceStuff("test: {myobj.deep.test}", "myobj.deep.test", "my value");
See this SO question about curly braces. Perhaps your browser of choice isn't as understanding as chrome is?
You need to escape the '.' characters in the string you're passing in as the fieldName parameter. Ditto for any other special regex characters that you want to be interpreted literally. Basically, fieldName is being treated as part of a regex pattern.
If you don't want fieldName to be evaluated as regex code, you might want to consider using string manipulation for this instead.
Edit: I just ran your code in FireFox and it worked perfectly. You may have something else going on here.

Create RegExps on the fly using string variables

Say I wanted to make the following re-usable:
function replace_foo(target, replacement) {
return target.replace("string_to_replace",replacement);
}
I might do something like this:
function replace_foo(target, string_to_replace, replacement) {
return target.replace(string_to_replace,replacement);
}
With string literals this is easy enough. But what if I want to get a little more tricky with the regex? For example, say I want to replace everything but string_to_replace. Instinctually I would try to extend the above by doing something like:
function replace_foo(target, string_to_replace, replacement) {
return target.replace(/^string_to_replace/,replacement);
}
This doesn't seem to work. My guess is that it thinks string_to_replace is a string literal, rather than a variable representing a string. Is it possible to create JavaScript regexes on the fly using string variables? Something like this would be great if at all possible:
function replace_foo(target, string_to_replace, replacement) {
var regex = "/^" + string_to_replace + "/";
return target.replace(regex,replacement);
}
There's new RegExp(string, flags) where flags are g or i. So
'GODzilla'.replace( new RegExp('god', 'i'), '' )
evaluates to
zilla
With string literals this is easy enough.
Not really! The example only replaces the first occurrence of string_to_replace. More commonly you want to replace all occurrences, in which case, you have to convert the string into a global (/.../g) RegExp. You can do this from a string using the new RegExp constructor:
new RegExp(string_to_replace, 'g')
The problem with this is that any regex-special characters in the string literal will behave in their special ways instead of being normal characters. You would have to backslash-escape them to fix that. Unfortunately, there's not a built-in function to do this for you, so here's one you can use:
function escapeRegExp(s) {
return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
}
Note also that when you use a RegExp in replace(), the replacement string now has a special character too, $. This must also be escaped if you want to have a literal $ in your replacement text!
function escapeSubstitute(s) {
return s.replace(/\$/g, '$$$$');
}
(Four $s because that is itself a replacement string—argh!)
Now you can implement global string replacement with RegExp:
function replace_foo(target, string_to_replace, replacement) {
var relit= escapeRegExp(string_to_replace);
var sub= escapeSubstitute(replacement);
var re= new RegExp(relit, 'g');
return target.replace(re, sub);
}
What a pain. Luckily if all you want to do is a straight string replace with no additional parts of regex, there is a quicker way:
s.split(string_to_replace).join(replacement)
...and that's all. This is a commonly-understood idiom.
say I want to replace everything but string_to_replace
What does that mean, you want to replace all stretches of text not taking part in a match against the string? A replacement with ^ certainly doesn't this, because ^ means a start-of-string token, not a negation. ^ is only a negation in [] character groups. There are also negative lookaheads (?!...), but there are problems with that in JScript so you should generally avoid it.
You might try matching ‘everything up to’ the string, and using a function to discard any empty stretch between matching strings:
var re= new RegExp('(.*)($|'+escapeRegExp(string_to_find)+')')
return target.replace(re, function(match) {
return match[1]===''? match[2] : replacement+match[2];
});
Here, again, a split might be simpler:
var parts= target.split(string_to_match);
for (var i= parts.length; i-->0;)
if (parts[i]!=='')
parts[i]= replacement;
return parts.join(string_to_match);
As the others have said, use new RegExp(pattern, flags) to do this. It is worth noting that you will be passing string literals into this constructor, so every backslash will have to be escaped. If, for instance you wanted your regex to match a backslash, you would need to say new RegExp('\\\\'), whereas the regex literal would only need to be /\\/. Depending on how you intend to use this, you should be wary of passing user input to such a function without adequate preprocessing (escaping special characters, etc.) Without this, your users may get some very unexpected results.
Yes you can.
https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
function replace_foo(target, string_to_replace, replacement) {
var regex = new RegExp("^" + string_to_replace);
return target.replace(regex, replacement);
}
A really simple solution to this is this:
function replace(target, string_to_replace, replacement) {
return target.split(string_to_replace).join(replacement);
}
No need for Regexes at all
It also seems to be the fastest on modern browsers https://jsperf.com/replace-vs-split-join-vs-replaceall
I think I have very good example for highlight text in string (it finds not looking at register but highlighted using register)
function getHighlightedText(basicString, filterString) {
if ((basicString === "") || (basicString === null) || (filterString === "") || (filterString === null)) return basicString;
return basicString.replace(new RegExp(filterString.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\\\$&'), 'gi'),
function(match)
{return "<mark>"+match+"</mark>"});
}
http://jsfiddle.net/cdbzL/1258/

Categories