I am willing to do the following:
I have :
var distance1 = "5.5 Km";
var distance2 = "5,5 Km";
//The below works as expected and returns 5.5
var finalDistance = distance1.replace( /[^\d\.]*/g, '');
//However the below doesn't and print 55 instead
distance2.replace( /[^\d\.]*/g, '');
//I've tried the below too and it throws 5,5. But I want 5.5
distance2.replace( /[^\d\.\,]*/g, '');
First, replace all occurences of , with ., then replace non-digit characters (except .) with '':
distance2 = distance2.replace( /,/g, '.').replace(/[^\d\.]+/g, '');
where:
/,/g : matches all commas ',' that will be replaced by '.'
/[^\d\.]+ : matches any sequence of non-digit and non-dot ('.') characters that will be removed (replaced by the empty string '').
The first replace transform "5,55 KM" to "5.55 KM" then the second transform the latter to "5.55".
Note: if you only have one comma, or only interested in the first encountered one, then you could use: replace(',', '.') instead of replace(/,/g, '.').
If you are using only the float representation, you could use parseFloat instead of the second replace:
var number = parseFloat(distance2.replace(/,/g, '.'));
replace works by saying "find this string and replace with this string". The first parameter is what you want to find, the second is what to replace it with. So in your code you're replacing the , with nothing:
distance2.replace( /[^\d\.]*/g, '');
It also doesn't edit the string "in-place", so you need to assign the distance2 variable to the return value. Also, for a simple job like this you don't need to use regex. You can just input a string as the first parameter and replace will find all matches for that. This is how I would do this:
distance2 = distance2.replace(',', '.');
Further reading:
https://www.w3schools.com/jsref/jsref_replace.asp
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace
you need to reassign the replace value to the variable.
i.e.
distance2 = distance2.replace( /[^\d\.]*/g, '');
Related
I have this string:
var s = '/channels/mtb/videos?page=2&per_page=100&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true'
I want to repace per_page number (in this case 100, but it can be any number from 1-100, maybe more?)
I can select first part of the string with:
var s1 = s.substr(0, s.lastIndexOf('per_page=')+9)
which give me:
/channels/mtb/videos?page=2&per_page=
but how would I select next '&' after that so I can replace number occurrence?
dont assume same order of parameters!
You can use following regex to replace the content you want.
regex:- /per_page=[\d]*/g(this is only for your requirement)
var new_no=12; //change 100 to 12
var x='/channels/mtb/videos?page=2&per_page=100&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true';
var y=x.replace(/per_page=[\d]*/g,'per_page='+new_no);
console.log(y);
Explanation:-
/per_page=[\d]*/g
/ ----> is for regex pattern(it inform that from next character onward whatever it encounter will be regex pattern)
per_page= ----> try to find 'per_page=' in string
[\d]* ----> match 0 or more digit (it match until non digit encounter)
/g ---->/ to indicate end of regex pattern and 'g' is for global means find in all string(not only first occurrence)
Use replace with a regular expression to find the numbers after the text per_page=. Like this:
s.replace(/per_page=\d+/,"per_page=" + 33)
Replace the 33 with the number you want.
Result:
"/channels/mtb/videos?page=2&per_page=33&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true"
Start with the index from the lastIndexOf-per_page instead of 0.
Get the index of the first & and create a substr s2 to the end.
Then concat s1 + nr + s2.
I would not use regex, because it is much slower for this simple stuff.
With Array.filter you can do this, where one split the text into key/value pairs, and filter out the one that starts with per_page=.
Stack snippet
var s = '/channels/mtb/videos?page=2&per_page=100&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true'
var kv_pairs = s.split('&');
var s2 = s.replace((kv_pairs.filter(w => w.startsWith('per_page=')))[0],'per_page=' + 123);
//console.log(s2);
var matches = /(.*\bper_page=)(\d+)(.*)/;
if (matches) {
s = matches[0] + newValue + matches[2];
}
var data = this.state.registerMobile;
//My data will be like +91 345 45-567
data.replace('-','');
It is not removing '-' and i am trying to remove spaces also in between.It's not working.
For that, you need to assign the result of replace to some variable, replace will not do the changes in same variable, it will return the modified value. So use it like this:
var data = this.state.registerMobile;
data = data.replace('-', '');
console.log('updated data', data);
Check the example:
a = '+91 12345678';
b = a.replace('+', '');
console.log('a', a );
console.log('b', b );
String.prototype.replace() does not change the original string but returns a new one. Its first argument is either of the following:
regexp (pattern)
A RegExp object or literal. The match or matches are replaced with newSubStr or the value returned by the specified function.
substr (pattern)
A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.
So if you want to replace hypens and whitespaces, you have to use the following:
var data = this.state.registerMobile;
data = data.replace(/\s|-/g, '');
I am trying to remove some spaces from a few dynamically generated strings. Which space I remove depends on the length of the string. The strings change all the time so in order to know how many spaces there are, I iterate over the string and increment a variable every time the iteration encounters a space. I can already remove all of a specific type of character with str.replace(' ',''); where 'str' is the name of my string, but I only need to remove a specific occurrence of a space, not all the spaces. So let's say my string is
var str = "Hello, this is a test.";
How can I remove ONLY the space after the word "is"? (Assuming that the next string will be different so I can't just write str.replace('is ','is'); because the word "is" might not be in the next string).
I checked documentation on .replace, but there are no other parameters that it accepts so I can't tell it just to replace the nth instance of a space.
If you want to go by indexes of the spaces:
var str = 'Hello, this is a test.';
function replace(str, indexes){
return str.split(' ').reduce(function(prev, curr, i){
var separator = ~indexes.indexOf(i) ? '' : ' ';
return prev + separator + curr;
});
}
console.log(replace(str, [2,3]));
http://jsfiddle.net/96Lvpcew/1/
As it is easy for you to get the index of the space (as you are iterating over the string) , you can create a new string without the space by doing:
str = str.substr(0, index)+ str.substr(index);
where index is the index of the space you want to remove.
I came up with this for unknown indices
function removeNthSpace(str, n) {
var spacelessArray = str.split(' ');
return spacelessArray
.slice(0, n - 1) // left prefix part may be '', saves spaces
.concat([spacelessArray.slice(n - 1, n + 1).join('')]) // middle part: the one without the space
.concat(spacelessArray.slice(n + 1)).join(' '); // right part, saves spaces
}
Do you know which space you want to remove because of word count or chars count?
If char count, you can Rafaels Cardoso's answer,
If word count you can split them with space and join however you want:
var wordArray = str.split(" ");
var newStr = "";
wordIndex = 3; // or whatever you want
for (i; i<wordArray.length; i++) {
newStr+=wordArray[i];
if (i!=wordIndex) {
newStr+=' ';
}
}
I think your best bet is to split the string into an array based on placement of spaces in the string, splice off the space you don't want, and rejoin the array into a string.
Check this out:
var x = "Hello, this is a test.";
var n = 3; // we want to remove the third space
var arr = x.split(/([ ])/); // copy to an array based on space placement
// arr: ["Hello,"," ","this"," ","is"," ","a"," ","test."]
arr.splice(n*2-1,1); // Remove the third space
x = arr.join("");
alert(x); // "Hello, this isa test."
Further Notes
The first thing to note is that str.replace(' ',''); will actually only replace the first instance of a space character. String.replace() also accepts a regular expression as the first parameter, which you'll want to use for more complex replacements.
To actually replace all spaces in the string, you could do str.replace(/ /g,""); and to replace all whitespace (including spaces, tabs, and newlines), you could do str.replace(/\s/g,"");
To fiddle around with different regular expressions and see what they mean, I recommend using http://www.regexr.com
A lot of the functions on the JavaScript String object that seem to take strings as parameters can also take regular expressions, including .split() and .search().
I have a string like
5|10|20|200|300
and i want to get the First Digit Before | and last digit after | that is 5 and 300.
How would I use regex in javascript to return that numbers??
This simplest regex will return the two matches 5 and 300:
^\d+|\d+$
See the matches in the demo.
In JS:
result = yourString.match(/^\d+|\d+$/g);
Explanation
^\d+ matches the beginning of the string and some digits (the 5)
OR |
\d+$ matches some digits and the end of the string
JavaScript only keeps the last capture for (...)+, so you can write
var m = "5|10|20|200|300".match(/(\d+)(\|(\d+))+/);
Then m[1] is "5" and m[3] is "300"
var string = '5|10|20|200|300';
var array = string.split('|');
//array[0] = '5';
//array[array.length-1] = '300';
It's not regex I know, but I've always found split easier to work with in most cases.
Convert the string into an array using split() method
var str="5|10|20|200|300";
var res_array = str.split("|");
now to get first and last value of an array:::
alert("First value is"+ res_array[0]);
alert("Last value is"+ res_array[arr.length - 1]);
I've been trying to find a way to match a number in a Javascript string that is surrounded by parenthesis at the end of the string, then increment it.
Say I have a string:
var name = "Item Name (4)";
I need a RegExp to match the (4) part, and then I need to increment the 4 then put it back into the string.
This is the regex I have so far:
\b([0-9]+)$\b
This regex does not work. Furthermore, I do not know how to extract the integer retrieved and put it back in the same location in the string.
Thanks.
The replace method can take a function as its second argument. It gets the match (including submatches) and returns the replacement string. Others have already mentioned that the parentheses need to be escaped.
"Item Name (4)".replace(/\((\d+)\)/, function(fullMatch, n) {
return "(" + (Number(n) + 1) + ")";
});
I can can only think of a way of doing it in three steps: Extract, increment and replace.
// Tested on rhino
var name = "Item Name (4)";
var re = /\((\d+)\)/;
match = re.exec(name);
number = parseInt(match[1]) + 1;
name = name.replace(re, "(" + number + ")");
The important parts of the pattern:
You need to escape the parens to match literal parens
You also need the to use parens to capture the number so that you can extract it from the match.
\d matches a digit and is shorter and more common than writing out [0-9].
In order this pattern to work you shoud escape parenthesis. In addition \b and $ are unneeded. Thus
var s = "Item Name (4)";
var match = /\((\d+)\)/.exec( s );
var n = Number(match[1])+1;
alert( s.replace( /\(\d+\)/, '('+n+')' ) );
Solution by david.clarke (tested)
"Item Name (4)".replace(/\(([0-9]+)\)/, '('+(1+RegExp.$1) + ')');
But I think it is too concise
UPD: It turned out that RegExp.$1 can't be used as part of replace parameter, because it works only in Opera
'var name = "Item Name (4)"'.replace(/\(([\d]+)\)/, 1 + $1);
(untested)