javascript regexp replace not working, but string replace works - javascript

I'm working with jQuery and am trying to write a pattern replace, but it doesn't work. I have this:
var $featured_rewrite = $('#featured').not('.slideshow');
$featured_rewrite.children().attr('href', $featured_rewrite.find('img').attr('src').replace('/-[0-9]+x[0-9]+\./i', '.'));
I don't understand why something like this works:
.replace('-500x277.', '.')
but not this, which I even checked with a tool and made sure it was valid and works:
.replace('/-[0-9]+x[0-9]+\./i', '.')

'/-[0-9]+x[0-9]+\./i' is a string.
/-[0-9]+x[0-9]+\./i is regex.
"hi".match('/hi/') // returns null
"hi".match(/hi/) // returns ["hi"]
Edit: Also, just to be clear, there's nothing wrong with your regex other than the quotes. You may want to consider using /g (i.e. /gi at the end) if you need to replace more than one match, but that's it.

Related

Why would the replace with regex not work even though the regex does?

There may be a very simple answer to this, probably because of my familiarity (or possibly lack thereof) of the replace method and how it works with regex.
Let's say I have the following string: abcdefHellowxyz
I just want to strip the first six characters and the last four, to return Hello, using regex... Yes, I know there may be other ways, but I'm trying to explore the boundaries of what these methods are capable of doing...
Anyway, I've tinkered on http://regex101.com and got the following Regex worked out:
/^(.{6}).+(.{4})$/
Which seems to pass the string well and shows that abcdef is captured as group 1, and wxyz captured as group 2. But when I try to run the following:
"abcdefHellowxyz".replace(/^(.{6}).+(.{4})$/,"")
to replace those captured groups with "" I receive an empty string as my final output... Am I doing something wrong with this syntax? And if so, how does one correct it, keeping my original stance on wanting to use Regex in this manner...
Thanks so much everyone in advance...
The code below works well as you wish
"abcdefHellowxyz".replace(/^.{6}(.+).{4}$/,"$1")
I think that only use ()to capture the text you want, and in the second parameter of replace(), you can use $1 $2 ... to represent the group1 group2.
Also you can pass a function to the second parameter of replace,and transform the captured text to whatever you want in this function.
For more detail, as #Akxe recommend , you can find document on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace.
You are replacing any substring that matches /^(.{6}).+(.{4})$/, with this line of code:
"abcdefHellowxyz".replace(/^(.{6}).+(.{4})$/,"")
The regex matches the whole string "abcdefHellowxyz"; thus, the whole string is replaced. Instead, if you are strictly stripping by the lengths of the extraneous substrings, you could simply use substring or substr.
Edit
The answer you're probably looking for is capturing the middle token, instead of the outer ones:
var str = "abcdefHellowxyz";
var matches = str.match(/^.{6}(.+).{4}$/);
str = matches[1]; // index 0 is entire match
console.log(str);

Regex: get string between last character occurence before a comma

I need some help with Regex.
I have this string: \\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam
and want to get the result: ["dolor", "conseteteur", "diam"]So in words the word between the last backslash and a comma or the end.
I've already figured out a working test, but because of reasons it won't work in neitherChrome (v44.0.2403.130) nor IE (v11.0.9600.17905) console.There i'm getting the result: ["\loremipsumdolor,", "\sitametconseteteur,", "\sadipscingelitrseddiam"]
Can you please tell me, why the online testers aren't working and how i can achieve the right result?
Thanks in advance.
PS: I've tested a few online regex testers with all the same result. (regex101.com, regexpal.com, debuggex.com, scriptular.com)
The string
'\\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam'
is getting escaped, if you try the following in the browser's console you'll see what happens:
var s = '\\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam'
console.log(s);
// prints '\loremipsumdolor,\sitametconseteteur,\sadipscingelitrseddiam'
To use your original string you have to add additional backslashes, otherwise it becomes a different one because it tries to escape anything followed by a single backslash.
The reason why it works in regexp testers is because they probably sanitize the input string to make sure it gets evaluated as-is.
Try this (added an extra \ for each of them):
str = '\\\\lorem\\ipsum\\dolor,\\\\sit\\amet\\conseteteur,\\\\sadipscing\\elitr\\sed\\diam'
re = /\\([^\\]*)(?:,|$)/g
str.match(re)
// should output ["\dolor,", "\conseteteur,", "\diam"]
UPDATE
You can't prevent the interpreter from escaping backslashes in string literals, but this functionality is coming with EcmaScript6 as String.raw
s = String.raw`\\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam`
Remember to use backticks instead of single quotes with String.raw.
It's working in latest Chrome, but I can't say for all other browsers, if they're moderately old, it probably isn't implemented.
Also, if you want to avoid matching the last backslash you need to:
remove the \\ at the start of your regexp
use + instead of * to avoid matching the line end (it will create an extra capture)
use a positive lookahead ?=
like this
s = String.raw`\\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam`;
re = /([^\\]+)(?=,|$)/g;
s.match(re);
// ["dolor", "conseteteur", "diam"]
You may try this,
string.match(/[^\\,]+(?=,|$)/gm);
DEMO

What seems to be a correct regex doesn't work in replace function

I am trying to match three consecutive dots (".") followed optionally by a space.
My idea was the following:
\.\.\.\s?
Tested it here and seems to do exactly as expected.
But then when I try to use it in the replace function with javascript it doesn't seem to work, it's quite weird unless I'm missing something silly:
replace("\.\.\.\s?", "")
Doesn't work, see live demo here.
What am I missing?
The regex shouldn't be in quotes. Try...
mystr.replace(/\.\.\.\s?/, "")
jsfiddle
this should work $('div').text("... hi".replace(/\.\.\.\s?/, ""));
String.replace() takes either a string or a regular expression as the first argument. If it is a string then it is searched for verbatim. https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/replace
The first parameter of String.replace must be a RegExp object, not String. Change it to:
$('div').text("... hi".replace(/\.\.\.\s?/, ""));
Or,
$('div').text("... hi".replace(new RegExp("\\.\\.\\.\\s?"), ""));
$('div').text("... hi".replace(/\.{3}/gi, ""));
Slightly optimized regular expression.

js: special char in regex

in my regular expression, I tried to remove all "{" and "}"s from a string.
Pushing the script with packer/minimizer scripts, breaks them.
That's why I'd like to know about a better and more compatible way of writing:
mystring.replace(/\{/g,"");?
You can just use a string instead of a regex. I'm not sure if this is "better" but it should not break when minified. If you provide the minified example, we may be able to help with that.
mystring.replace("}", "").replace("{", "");
Edit:
If the curly bracket is causing the problem, perhaps this would work...
var reg = new RegExp("\\{|\\}", "g");
mystring.replace(reg, "");
Example from the console...
> var mystring = "test{foo}bar{baz}";
> var reg = new RegExp("\\{|\\}", "g");
> mystring.replace(reg, "");
"testfoobarbaz"
Lastly, you could do this:
If a regex really wont work for you, this will replace all {'s and }'s
It is probably a horrible solution, considering performance, but...
mystring.split("}").join("").split("{").join("");
You could try
mystring.replace(/\u007B/g,"");
This uses unicode rather than the actual symbol, so your packer won't get confused. If you want to replace more than one character in a single statement, you can use the "or" pipe:
mystring.replace(/\u007B|\u007D/g,"");
{ = \u007B
} = \u007D
For more unicode codes see:
http://www.unicode.org/charts/PDF/U0000.pdf
After re-reading the question, it sounds like you've found a bug with the minifier/packer. My first suggestion would be to use a better minimizer that doesn't have these issues, but if you're stuck with what you're using, you could try using the unicode escape sequence in the regular expression:
mystring.replace(/\u007b/g, '');
Alternatively, you could try String.prototype.split and Array.prototype.join:
mystring.split('{').join('');

Javascript .test either returns nothing or false, when regex matches the tested string?

I'm using javascript's inbuilt .test() function to test whether a string or regex matches. I took the regex from RegexLib, so I know that it matches the string it's tested against (in this case joe#aol.com), however it either returns false or nothing at all.
Here's my code:
var string = "joe#aol.com";
var pattern = [\w-]+#([\w-]+\.)+[\w-]+/i;
var match = pattern.test(string);
document.write(match);
When the regex is encased in quotes, the test returns false, when it's not encased in anything, it returns nothing.
What I've tried so far:
Simply using a single line, var match = '[\w-]+#([\w-]+\.)+[\w-]+/i'.test("joe#aol.com");.
Using both ' single quotes and " double quotes for both regex and string.
Appending the regex with /i and /g.
I honestly don't know what's causing this issue, so any help would be great. It could be a complete rookie mistake, a forgotten syntax perhaps.
Here's a link to the jsFiddle I made up for you to play around with if you think you've got some idea of how to fix this up: http://jsfiddle.net/wFhEJ/1/
You missed the opening slash for a regexp. The notation for a regexp is:
/regexp/flags
What happened with enclosing the regexp is that it became a string, and on jsFiddle String.prototype.test has been set by MooTools. MooTools seems to provide a String.prototype.test function, but it's not the same as RegExp.prototype.test.
http://jsfiddle.net/wFhEJ/2/
var string = "joe#aol.com";
var pattern = /[\w-]+#([\w-]+\.)+[\w-]+/i;
var match = pattern.test(string);
document.write(match);
Do note though that document.write is frowned upon. You might rather want document.body.appendChild(document.createTextNode(match)) or something alike.

Categories

Resources