String.replace regex is not replacing `*` in string - javascript

I have a string that comes in and I am running a string.replace on it and it is not removing the * character from the string but it is removing the | character.
var s = "|*55.6";
s = s.replace(/[^0-9.]/, "");
console.log(s);

Use a global regular expression (/.../g) if you want to replace more than a single match:
s = s.replace(/[^0-9.]+/g, "") //=> "55.6"
Edit: Following your pattern with + (which matches more than one of a pattern in succession) will produce fewer matches and thus make the replacement with "" run more efficiently than using the g flag alone. I would use them both together. Credit to Jai for using this technique in his answer before me.
Demo Snippet
var s = "|*55.6"
s = s.replace(/[^0-9.]+/g, "")
console.log(s) //=> "55.6"

It's because replace executed just once. Use g option to replace every match.
s = s.replace(/[^0-9.]/g, "");

You haven't used a global flag for your regex, that is why the first occurrence was replaced, than the operation ended.
var s = "|*55.6";
s = s.replace(/[^\d.]/g, "");
console.log(s);
Using + quantifier alone wouldn't help if you have separate occurrences of [^\d.], though would be better to use together with g flag. For example;
var s = "|*55.6a"
s = s.replace(/[^0-9.]+/, "")
console.log(s) //=> "55.6a not OK

You need to use a global (g) flag / modifier or a plus (+) quantifier when replacing the string;
var s = "|*55.6";
s = s.replace(/[^0-9.]/g, "");
console.log(s);
var s = "|*55.6";
s = s.replace(/[^0-9.]+/, "");
console.log(s);

You are missing + to look for one or more occurrences:
var s = "|*55.6";
s = s.replace(/[^0-9.]+/, "");
console.log(s);
Also if you are interested to takeout the numbers, then you can use .match() method:
var s = "|*55.6";
s = s.match(/[(0-9.)]+/g)[0];
console.log(s);

Some answer mentioned the Quantifiers +, but it will still only replace the first match:
console.log("|*45.6abc".replace(/[^0-9.]+/, ""))
If you need to remove all non-digital chars(except .), the modifier/flag g is still required
console.log("|*45.6,34d".replace(/[^0-9.]+/g, ""));

Related

how to combine regEx expressions

How do I take each of these and combine them into a single regEx expression?
var t = "<test>";
t = t.replace(/^</, '');
t = t.replace(/>+$/, '');
which results in t equal to test without the <>
You can use pipe |. In regex it means OR:
t = "<test>>".replace(/^<|>+$/g, "");
// "test"
But of course, you can use another ways like:
t = "<test>>".replace(/[<>]/g, "");
// "test"
or even with match:
t = "<test>>".match(/\w+/)[0];
// "test"
Make sure you've added the g-global flag when needed. This flag stands for all occurrences.
If I understand correctly you only want to replace beginning '<' symbols and ending '>' symbols, try this one [>$^<]
var t = "<test>";
t = t.replace('/[>$^<]/', '');
Try this
t = t.replace(/^</, '').replace(/>+$/, '');
If you want it in single line, use | to combine the regex.. Like this
t = t.replace(/^<|>+$/g, "");
or capture groups like this
t = t.replace(/^<(.*)>+$/g, '$1');

Getting each 'word' after every underscore in a string in Javascript using regex

I'm wanting to extract each block of alphanumeric characters that come after underscores in a Javascript string. I currently have it working using a combination of string methods and regex like so:
var string = "ignore_firstMatch_match2_thirdMatch";
var firstValGone = string.substr(string.indexOf('_'));
// returns "_firstMatch_match2_thirdMatch"
var noUnderscore = firstValGone.match(/[^_]+/g);
// returns ["firstMatch", "match2" , "thirdMatch"]
I'm wondering if there's a way to do it purely using regex? Best I've managed is:
var string = "ignore_firstMatch_match2_thirdMatch";
var matchTry = string.match(/_[^_]+/g);
// returns ["_firstMatch", "_match2", "_thirdMatch"]
but that returns the preceding underscore too. Given you can't use lookbehinds in JS I don't know how to match the characters after, but exclude the underscore itself. Is this possible?
You can use a capture group (_([^_]+)) and use RegExp#exec in a loop while pushing the captured values into an array:
var re = /_([^_]+)/g;
var str = 'ignore_firstMatch_match2_thirdMatch';
var res = [];
while ((m = re.exec(str)) !== null) {
res.push(m[1]);
}
document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>";
Note that using a string#match() with a regex defined with a global modifier /g will lose all the captured texts, that's why you cannot just use str.match(/_([^_]+)/g).
Since lookbehind is not supported in JS the only way I can think of is using a group like this.
Regex: _([^_]+) and capture group using \1 or $1.
Regex101 Demo
var myString = "ignore_firstMatch_match2_thirdMatch";
var myRegexp = /_([^_]+)/g;
match = myRegexp.exec(myString);
while (match != null) {
document.getElementById("match").innerHTML += "<br>" + match[0];
match = myRegexp.exec(myString);
}
<div id="match">
</div>
An alternate way using lookahead would be something like this.
But it takes long in JS. Killed my page thrice. Would make a good ReDoS exploit
Regex: (?=_([A-Za-z0-9]+)) and capture groups using \1 or $1.
Regex101 Demo
Why do you assume you need regex? a simple split will do the job:
string str = "ignore_firstMatch_match2_thirdMatch";
IEnumerable<string> matches = str.Split('_').Skip(1);

String : Replace function with expression in Javascript

A string representing a currency is to be converted to a number.
For example:
Input : "125.632.454.454.403,51"
Output expected : 125632454454403.51
Currently I am trying:
Trial 1)
a = "125.632.454.454.403,51";
a.replace(/./, '');
Result = "25.632.454.454.403,51"
Trial 2)
a = "125.632.454.454.403,51";
a.replace(/./g, '');
Result = ""
But I expect the replace function to find all the occurrences of "." and replace by "".
Trial 3)
a = "125.632.454.454.403,51";
a.replace(/,/, '');
Result = "125.632.454.454.40351"
I would be glad if I find a fix for this.
You need to use \. instead of .. The dot (.) matches a single character, without caring what that character is. Also you can do it with single replace() with callback .
var str = "125.632.454.454.403,51";
str = str.replace(/\.|,/g, function(m) {
return m == '.' ? '' : '.'
});
document.write(str);
try:
var str = "125.632.454.454.403,51" ;
var result = str.replace(/\./g,'').replace(/\,/g,'.');
console.log(Number(result))
replace returns the changed string, it does not change it in-place!
You can find this out, by refering to the documentation.
Use
var Result = a.split('.').join("");
console.log(Result);
. has specific meaning in a regex. It matches any character. You need to escape the dot if you are actually looking for the character itself
var a = "125.632.454.454.403,51";
var result = a.replace(/\./g,"");
You can also do (parseFloat(a.replace(/[^0-9]+/g,""))/100)
And if you have to do this for multiple currencies, I would recommend looking into autonumeric.js. It handles all this for you.

Use regex to remove "public://" from string

Im lost in part of this.
I want to remove the public:// in every link of an image like public://china-taxi_4.jpg
I have tried this but returns null:
var _img = 'public://china-taxi_4.jpg';
var regex = /(public:)(\/\w+)/;
var matches = _img.match(regex);
console.log(matches);
Hope you can help.
I want to remove the 'public://' in every link of an image.
> var img = 'public://china-taxi_4.jpg';
> img.replace(/public:\/\/(?=\S+?\.jpg(?:\s|$))/, "")
'china-taxi_4.jpg'
It removes the word public:// only in the strings which ends with .jpg
You are removing a literal string, not a regular expression. So try:
var _img = 'public://china-taxi_4.jpg';
var result = _img.replace("public://","");
console.log(result);
Regexes are for matching complex expressions.
I think you're missing a slash, try:
var _img = 'public://china-taxi_4.jpg';
var regex = /(public:)(\/\/\w+)/;
var matches = _img.match(regex);
console.log(matches);
From Mozilla Developer Network String.prototype.replace():
Example: Defining the regular expression in replace()
In the following example, the regular expression is defined in
replace() and includes the ignore case flag.
var str = 'Twas the night before Xmas...';
var newstr = str.replace(/xmas/i, 'Christmas');
console.log(newstr);
This prints:
'Twas the night before Christmas...'
To match the beginning of a string, use ^
To escape characters that have special meaning in regexp like : and / so that regexp will match these literally, prepend \
This suggests:
var _img = 'public://china-taxi_4.jpg';
var newimg = _img.replace(/^public\:\/\//i, '');
Tested and working in chrome browser console window.
Note: This answer also matches an earlier comment by #dystroy, so I have marked it CW.
var re = /(public:)(\/\/[\w-.]+)/g;
See demo.
http://regex101.com/r/rA7aS3/9

Javascript Remove strings in beginning and end

base on the following string
...here..
..there...
.their.here.
How can i remove the . on the beginning and end of string like the trim that removes all spaces, using javascript
the output should be
here
there
their.here
These are the reasons why the RegEx for this task is /(^\.+|\.+$)/mg:
Inside /()/ is where you write the pattern of the substring you want to find in the string:
/(ol)/ This will find the substring ol in the string.
var x = "colt".replace(/(ol)/, 'a'); will give you x == "cat";
The ^\.+|\.+$ in /()/ is separated into 2 parts by the symbol | [means or]
^\.+ and \.+$
^\.+ means to find as many . as possible at the start.
^ means at the start; \ is to escape the character; adding + behind a character means to match any string containing one or more that character
\.+$ means to find as many . as possible at the end.
$ means at the end.
The m behind /()/ is used to specify that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary.
The g behind /()/ is used to perform a global match: so it find all matches rather than stopping after the first match.
To learn more about RegEx you can check out this guide.
Try to use the following regex
var text = '...here..\n..there...\n.their.here.';
var replaced = text.replace(/(^\.+|\.+$)/mg, '');
Here is working Demo
Use Regex /(^\.+|\.+$)/mg
^ represent at start
\.+ one or many full stops
$ represents at end
so:
var text = '...here..\n..there...\n.their.here.';
alert(text.replace(/(^\.+|\.+$)/mg, ''));
Here is an non regular expression answer which utilizes String.prototype
String.prototype.strim = function(needle){
var first_pos = 0;
var last_pos = this.length-1;
//find first non needle char position
for(var i = 0; i<this.length;i++){
if(this.charAt(i) !== needle){
first_pos = (i == 0? 0:i);
break;
}
}
//find last non needle char position
for(var i = this.length-1; i>0;i--){
if(this.charAt(i) !== needle){
last_pos = (i == this.length? this.length:i+1);
break;
}
}
return this.substring(first_pos,last_pos);
}
alert("...here..".strim('.'));
alert("..there...".strim('.'))
alert(".their.here.".strim('.'))
alert("hereagain..".strim('.'))
and see it working here : http://jsfiddle.net/cettox/VQPbp/
Slightly more code-golfy, if not readable, non-regexp prototype extension:
String.prototype.strim = function(needle) {
var out = this;
while (0 === out.indexOf(needle))
out = out.substr(needle.length);
while (out.length === out.lastIndexOf(needle) + needle.length)
out = out.slice(0,out.length-needle.length);
return out;
}
var spam = "this is a string that ends with thisthis";
alert("#" + spam.strim("this") + "#");
Fiddle-ige
Use RegEx with javaScript Replace
var res = s.replace(/(^\.+|\.+$)/mg, '');
We can use replace() method to remove the unwanted string in a string
Example:
var str = '<pre>I'm big fan of Stackoverflow</pre>'
str.replace(/<pre>/g, '').replace(/<\/pre>/g, '')
console.log(str)
output:
Check rules on RULES blotter

Categories

Resources