Javascript Replace with Regex Match Not Working - javascript

I'm trying to truncate some longitude coordinates without any rounding issues. I thought replace() would be the simplest way to do this.
My regex is correct, but I'm apparently not using replace correctly.
Here's my stripped down example. I need to strip all decimal points after the 8th position
var truncRegex = /-?\d+?\.\d{8}/;
console.log('-81.82297519999997'.replace(truncRegex, '$1'));
What's happening is replace() is stripping the match and leaving me with the remainder prepended with "$1". The result is:
$1999997

You've got some answers of RegExp. Alternatively, you could just find the index of the point and retrieve a substring, if you don't care about rounding.
var str = '-81.82297519999997';
var truncated = str.substring(0, str.indexOf('.') + 9); // this will give you 8 fractions
console.log(truncated); // "-81.82297519"

You must add matching groups in parentheses to match something that you can refer to with $1 while replacing. For example:
var truncRegex = /(-?\d+?\.\d{8})\d*/;
console.log('-81.82297519999997'.replace(truncRegex, '$1'));
replace() function replaces everything it matches based on regular expression. Your code simply replaces -DD.DDDDDDDD with '$1' string.
You can still use expression you provided, but you will have to use match, not replace, e.g.:
var truncRegex = /-?\d+?\.\d{8}/;
console.log('-81.82297519999997'.match(truncRegex)[0]);

var s = '81.82297519999997';
// Returns "-81.82297519"
s.replace(/(-?\d+\.\d{8})\d*/, '$1');

(-?\d+?\.\d{8})|.*
Try this.Replace by $1.See demo.
https://regex101.com/r/eZ0yP4/17
var re = /(-?\d+?\.\d{8})|.*/mg;
var str = '-81.82297519999997';
var subst = '$1';
var result = str.replace(re, subst);

Related

javascript regex to find only numbers with hyphen from a string content

In Javascript, from a string like this, I am trying to extract only the number with a hyphen. i.e. 67-64-1 and 35554-44-04. Sometimes there could be more hyphens.
The solvent 67-64-1 is not compatible with 35554-44-04
I tried different regex but not able to get it correctly. For example, this regex gets only the first value.
var msg = 'The solvent 67-64-1 is not compatible with 35554-44-04';
//var regex = /\d+\-?/;
var regex = /(?:\d*-\d*-\d*)/;
var res = msg.match(regex);
console.log(res);
You just need to add the g (global) flag to your regex to match more than once in the string. Note that you should use \d+, not \d*, so that you don't match something like '3--4'. To allow for processing numbers with more hyphens, we use a repeating -\d+ group after the first \d+:
var msg = 'The solvent 67-64-1 is not compatible with 23-35554-44-04 but is compatible with 1-23';
var regex = /\d+(?:-\d+)+/g;
var res = msg.match(regex);
console.log(res);
It gives only first because regex work for first element to test
// g give globel access to find all
var regex = /(?:\d*-\d*-\d*)/g;

remove last part of string following '&&&' with JavaScript Regex

I'm trying to use a regex in JS to remove the last part of a string. This substring starts with &&&, is followed by something not &&&, and ends with .pdf.
So, for example, the final regex should take a string like:
parent&&&child&&&grandchild.pdf
and match
parent&&&child
I'm not that great with regex's, so my best effort has been something like:
.*?(?:&&&.*\.pdf)
Which matches the whole string. Can anyone help me out?
You may use this greedy regex either in replace or in match:
var s = 'parent&&&child&&&grandchild.pdf';
// using replace
var r = s.replace(/(.*)&&&.*\.pdf$/, '$1');
console.log(r);
//=> parent&&&child
// using match
var m = s.match(/(.*)&&&.*\.pdf$/)
if (m) {
console.log(m[1]);
//=> parent&&&child
}
By using greedy pattern .* before &&& we make sure to match **last instance of &&& in input.
You want to remove the last portion, so replace it
var str = "parent&&&child&&&grandchild.pdf"
var result = str.replace(/&&&[^&]+\.pdf$/, '')
console.log(result)

Java Script - Regular Expression matching a word in a string

I am trying to find a match in a string with JavaScript. I want to work with the RegEx function.
My example (what I have tried):
var str = "hello.you";
var patt1 = '\\b' + str + '\\b';
var result = str.match(patt1);
But this does not give me the result which I except. I just want to print "you".
Thanks all in advance.
So you jumped right into a pretty advanced regex topic. You sort of want to do a lookahead (the word AFTER a given boundary character). The following will get you there:
let str = "hello.you",
myRegex = /(?<=\.)\w+/;
let theWord = str.match(myRegex);
console.log(theWord[0]);
... And what that does, is uses (?<=.) to indicate "something that comes after a period", followed by \w+ to indicate a word.
I'd recommend using a regex tester, and build from that. I use https://www.regextester.com/

RegExp to filter characters after the last dot

For example, I have a string "esolri.gbn43sh.earbnf", and I want to remove every character after the last dot(i.e. "esolri.gbn43sh"). How can I do so with regular expression?
I could of course use non-RegExp way to do it, for example:
"esolri.gbn43sh.earbnf".slice("esolri.gbn43sh.earbnf".lastIndexOf(".")+1);
But I want a regular expression.
I tried /\..*?/, but that remove the first dot instead.
I am using Javascript. Any help is much appreciated.
I would use standard js rather than regex for this one, as it will be easier for others to understand your code
var str = 'esolri.gbn43sh.earbnf'
console.log(
str.slice(str.lastIndexOf('.') + 1)
)
Pattern Matching
Match a dot followed by non-dots until the end of string
let re = /\.[^.]*$/;
Use this with String.prototype.replace to achieve the desired output
'foo.bar.baz'.replace(re, ''); // 'foo.bar'
Other choices
You may find it is more efficient to do a simple substring search for the last . and then use a string slicing method on this index.
let str = 'foo.bar.baz',
i = str.lastIndexOf('.');
if (i !== -1) // i = -1 means no match
str = str.slice(0, i); // "foo.bar"

Regex or lastIndexOf when removing last instance of a string

I couldn't apply answers to other similar questions (trying to replace the last occurrence of a string) because I am having trouble with the syntax.
I'm trying to replace the last occurrence of a string. The value of the string is stored in a variable that is passed to the .replace() method like this:
var str += some additive strings;
var del = a string that lives within str; // the value is dynamic
str = str.replace(del$, ''); // this doesn't work to remove the last occurrence of `del` in str
As I understand it the $ argument looks for the last occurrence of a string within a regex; but I can't figure out how to use it alongside a variable passed to .replace(). Any suggestions?
If you want to use the RegExp with a $, do it like this:
var str += 'some additive strings';
var re = new RegExp('a string that lives within str$');
str = str.replace(re, '');
str = str.substring(0, str.length - del.length);
You can use lastIndexOf() with slice()
Example:
var str ="HI this is cool isn't it? cool";
var del='cool';// put whatever here
var index = test.lastIndexOf(del);
var length=del.length;
if(index!=-1)
var removeStr=test.substr(index,length);
str.replace(removeStr,''); // HI this is cool isn't it?
Mate, this is just an answer. You'll need to use it according to your needs.
Updated Live demo:http://jsfiddle.net/n2Kgn/2

Categories

Resources