I have a filename that can have multiple dots in it and could end with any extension:
tro.lo.lo.lo.lo.lo.png
I need to use a regex to replace the last occurrence of the dot with another string like #2x and then the dot again (very much like a retina image filename) i.e.:
tro.lo.png -> tro.lo#2x.png
Here's what I have so far but it won't match anything...
str = "http://example.com/image.png";
str.replace(/.([^.]*)$/, " #2x.");
any suggestions?
You do not need a regex for this. String.lastIndexOf will do.
var str = 'tro.lo.lo.lo.lo.lo.zip';
var i = str.lastIndexOf('.');
if (i != -1) {
str = str.substr(0, i) + "#2x" + str.substr(i);
}
See it in action.
Update: A regex solution, just for the fun of it:
str = str.replace(/\.(?=[^.]*$)/, "#2x.");
Matches a literal dot and then asserts ((?=) is positive lookahead) that no other character up to the end of the string is a dot. The replacement should include the one dot that was matched, unless you want to remove it.
Just use special replacement pattern $1 in the replacement string:
console.log("tro.lo.lo.lo.lo.lo.png".replace(/\.([^.]+)$/, "#2x.$1"));
// "tro.lo.lo.lo.lo.lo#2x.png"
You can use the expression \.([^.]*?):
str.replace(/\.([^.]*?)$/, "#2x.$1");
You need to reference the $1 subgroup to copy the portion back into the resulting string.
working demo http://jsfiddle.net/AbDyh/1/
code
var str = 'tro.lo.lo.lo.lo.lo.zip',
replacement = '#2x.';
str = str.replace(/.([^.]*)$/, replacement + '$1');
$('.test').html(str);
alert(str);
To match all characters from the beginning of the string until (and including) the last occurence of a character use:
^.*\.(?=[^.]*$) To match the last occurrence of the "." character
^.*_(?=[^.]*$) To match the last occurrence of the "_" character
Use \. to match a dot. The character . matches any character.
Therefore str.replace(/\.([^\.]*)$/, ' #2x.').
You could simply do like this,
> "tro.lo.lo.lo.lo.lo.zip".replace(/^(.*)\./, "$1#2x");
'tro.lo.lo.lo.lo.lo#2xzip'
Why not simply split the string and add said suffix to the second to last entry:
var arr = 'tro.lo.lo.lo.lo.lo.zip'.split('.');
arr[arr.length-2] += '#2x';
var newString = arr.join('.');
'tro.lo.lo.lo.lo.lo.png'.replace(/([^\.]+).+(\.[^.]+)/, "$1.#x2$2")
Related
Hava a string like this:
"let key1=value1; let key2=value2;"
I want to select the key and value as groups using regex, I've tried using look around.
/(\w+)(?=\=)(\w+);/g
but it doesn't work with me, any suggestions?
The following regex should do the trick: (let (\w+) ?= ?(\w+);?)+.
Each let statement will be a match where the key will be the group 2 and the value the group 3.
The (?=\=) expression part is a lookahead, a zero-width assertion, it does not consume text but requires it to be present on the right. When you say (?=\=)(\w+) you want \w+ pattern to start matching on =. As \w does not match =, your regex always fails.
Use
/(\w+)=(\w+);/g
JavaScript (borrowed from How do you access the matched groups in a JavaScript regular expression?):
var myString = "let key1=value1; let key2=value2;";
var myRegexp = /(\w+)=(\w+);/g;
match = myRegexp.exec(myString);
while (match != null) {
console.log(match[1] + "," + match[2]);
match = myRegexp.exec(myString);
}
To be more specific, we could use (\w+) ?= ?(\w+);?+
I want to know the regular expression for inserting characters BEFORE the matched characters from the Regular Expression. For example:
var string = "HelloYouHowAreYou"
var regEx = /[A-Z\s]/g //to identify capital letters, but want to insert a dash before them
string = string.replace(regEx,"-")
console.log(string)
How can I accompish this?
You could use a positive lookahead, which looks for the specified characters, but not insert it into the match group and prevent the first character to get a dash at the beginning of the string.
/(?!^)(?=[A-Z])/g
var string = "HelloYouHowAreYou",
regEx = /(?!^)(?=[A-Z])/g;
string = string.replace(regEx, "-");
console.log(string);
You just need to use $& backreference in the replacement pattern to refer to the whole match:
var string = "HelloYouHowAreYou"
var regEx = /[A-Z\s]/g;
string = string.replace(regEx,"-$&")
console.log(string)
If you want to avoid matching the uppercase ASCII letter at the beginning of the string, add a (?!^) at the beginning:
var string = "HelloYouHowAreYou"
var regEx = /(?!^)[A-Z\s]/g;
string = string.replace(regEx,"-$&")
console.log(string)
Note that \s matches whitespace. If you want to only match uppercase ASCII letters, use
/[A-Z]/g
Wiktor Stribiżew has a great answer already, but you can also pass a function to the replace method if you want to do additional manipulation of the string.
var string = "HelloYouHowAreYou"
var regEx = /[A-Z\s]/g //to identify capital letters, but want to insert a dash before them
function replacer(match) {
return ('-') + (match);
}
string = string.replace(regEx,replacer)
console.log(string)
I'm trying to match parts of code with regex. How can I match var, a, =, 2 and ; from
"var a = 2;"
?
I believe you want this regexp: /\S+/g
To break it down: \S selects all non-whitespace characters, + makes sure you it selects multiple non whitespace characters together (i.e. 'var'),
and the 'g' flag makes sure it selects all of the occurrences in the string, and instead of stopping at the first one which is the default behavior.
This is a helpful link for playing around until you find the right regexp: https://regex101.com/#javascript
var str = "var a = 2;";
// clean the duplicate whitespaces
var no_duplicate_whitespace = str.replace(new RegExp("\\s+", "g"), " ");
// and split by space
var tokens = no_duplicate_whitespace.split(" ");
Or as #kuujinbo pointed out:
str.split(/\s+/);
I've been searching for a solution but almost every one that I've come across with is about replacing a matching pattern with a previously known character.
For example:
var str = 'HMQ 2.. Elizabeth';
How do we catch multiple occurences of that dots in the string and replace them with only one? And it's also not specific to dots but any non-alphanumeric characters that we don't know which. Thank you.
Use a backreference. \1 in the regex refers to the first match group in the expression.
var str = 'HMQ 2.. Elizabetttth .';
var regex = /([^A-Za-z0-9])\1+/g;
var trimmed = str.replace(regex, "$1");
console.log( trimmed );
I have a text
test, text, 123, without last comma
I need it to be
test, text, 123 without last comma
(no comma after 123). How to achieve this using JavaScript?
str.replace(/,(?=[^,]*$)/, '')
This uses a positive lookahead assertion to replace a comma followed only by non-commata.
A non-regex option:
var str = "test, text, 123, without last comma";
var index = str.lastIndexOf(",");
str = str.substring(0, index) + str.substring(index + 1);
But I like the regex one. :-)
Another way to replace with regex:
str.replace(/([/s/S]*),/, '$1')
This relies on the fact that * is greedy, and the regex will end up matching the last , in the string. [/s/S] matches any character, in contrast to . that matches any character but new line.