How to remove thousand separaters in number using javascript? [duplicate] - javascript

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 2 years ago.
problem:
I want to remove the comma in a string and make it as a number.
It means,
234,345 should become 234345.
1,234 should become 1234
4,567,890 should become 4567890
I have created one code like this.
let a = "5,245"
function numberWithoutCommas(x) {
return x.replace(",","");
}
const b = parseInt(numberWithoutCommas(a))
console.log(typeof(b))
console.log(b)
This is failing when there more comma in the string.It means 1,234,567 gives 1234. So can someone help me to achieve it?

Splitting and joining should do the job
return x.split(',').join('');

You can simply parse to a number and use a regex
const s = ['5,332', '39,322,322,233']
function numberWithoutCommas(x) {
return Number(x.replace(/,/g, ''));
}
for (const a of s) {
const n = numberWithoutCommas(a);
console.log(n, typeof n);
}

passing string as a first argument to replace method will only replace the very first occurrence.
let str = '111,11,11,1';
str.replace(',','') // result:- 11111,11,1
use regex instead
str.replace(/,/g,'') //result:- 11111111
in your use case
function numberWithoutCommas(x) {
return x.replace(/,/g,"");
}

The replace() method searches a string for a specified value, or a
regular expression, and returns a new string where the specified
values are replaced.
Note: If you are replacing a value (and not a regular expression),
only the first instance of the value will be replaced. To replace all
occurrences of a specified value, use the global (g) modifier.
So, to replace all the occurrences of ,, we should rather use /,/g instead of just ,.
Then your code would be something like the following
let a = "1,234,567"
function numberWithoutCommas(x) {
return x.replace(/,/g,"");
}
const b = parseInt(numberWithoutCommas(a))
console.log(typeof(b))
console.log(b)
I hope this helps :)

Related

How to use a regular expression in this case [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 2 months ago.
I want to check if a string-variable (called string) matches the following string: L-62000-64-000_0
My code looks like this:
let string = "L-62000-64-000_05641";
let part = 64;
const filter = new RegExp("^L-\d{5}-${part}-.+");
if (string.match(filter)) {
console.log("yes");
}
It is important, that the string starts with "L-". After this there should be a number with five digits and again a hyphen. The following two digits depend on a variable. After the variable there is again a hyphen. The rest of the string is not important for me. That's why I use the ".+"
The problem is, that this doesn't work and i don't know why...
if you want to use the part variable in the string, you need to use `` instead of ""
const filter = new RegExp(`^L-\d{5}-${part}-.+`);
You also need to add double \\ in this case
let string = 'L-62000-64-000_05641';
let part = 64;
const filter = new RegExp(`^L-\\d{5}-${part}-.+$`);
if (string.match(filter)) {
console.log("yes");
} else {
console.log("no");
}

How to preserve character case using string.replace()? [duplicate]

This question already has answers here:
Replace text but keep case
(11 answers)
Closed 2 years ago.
I am attempting to write a function that will replace all of the vowels in a string with another arbitrary vowel which is selected by an end user. So far, I have been able to write a function that will replace all of the vowels regardless of case, but I would like to be able to preserve the case during replace().
Here is an example of what I am doing right now.
var selectedVowel = "a";
var vowels = /[aeiouAEIOU]/gi;
function rep(string){
let newString = string.replace(vowels, selectedVowel);
return newString;
}
rep("FooBar Exe. unIt");
// returns "FaaBar axe. anat"
// Intended output should return "FaaBar Axe. anAt"
I have tried using Regular Expressions to modify the search criteria for replace() and selectedVowel, but I can't figure out how to use the right regex characters to achieve that end.
I have also looked into methods that use split() to replace the first letter of a word, but this method seems to be limited to the string's indexes, which are not known at the time of the function call.
Any suggestions?
String.prototype.replace() takes a function in place of the substitution string, which is called for each match.
You could write a function that checks each match and replaces it with selectedVowel as-is or uppercased, depending on the case of the matched string.
A little trick to check if a character is upper/lowercase is to compare it to the upper/lowercased version of itself, as in match === match.toUpperCase().
var selectedVowel = "a";
var vowels = /[aeiouAEIOU]/gi;
function rep(string){
return string.replace(vowels, match => {
if (match === match.toUpperCase()) {
return selectedVowel.toUpperCase()
}
return selectedVowel
});
}
console.log(rep("FooBar Exe. unIt")) //=> "FaaBar Axa. anAt"

Modifying a string with letters, parentheses and numbers [duplicate]

This question already has answers here:
Regular Expression to get a string between parentheses in Javascript
(10 answers)
Closed 4 years ago.
How can I modify this string:
"SRID=4326;POINT (-21.93038619999993 64.1444948)"
so it will return
"-21.93038619999993 64.1444948"
(and then I can split that)?
The numbers in the string can be different.
I've tried using .replace & split, but I couldn't get it to work properly. How can I make this happen using Javascript?
You can try with match and regex:
"SRID=4326;POINT (-21.93038619999993 64.1444948)".match(/\(([^)]+)\)/)[1]
// "-21.93038619999993 64.1444948"
I am not good using REGEXP but this could be a solution with pure split.
Hope it helps :>
var str = "SRID=4326;POINT (-21.93038619999993 64.1444948)" ;
var newStr = str.split('(')[1].split(')')[0];
console.log(newStr)
var new_string = string.replace("SRID=4326;POINT (", "");
You can use a regular expression. The first number is put in first, the second number is put in second.
const INPUT = "SRID=4326;POINT (-21.93038619999993 64.1444948)";
const REGEX = /SRID=\d+;POINT \((.+) (.+)\)/
const [_, first, second] = INPUT.match(REGEX);
console.log(first);
console.log(second);

Use match in replace [duplicate]

This question already has answers here:
Javascript string replace method. Using matches in replacement string
(2 answers)
Closed 3 years ago.
I need to put every non-alphabetic character between spaces.
I want to do this using RegExp, and I understand it enouch to select them all (/(^a-zA-Z )/g).
Is there a way to use the original match inside the replace?
(something like)
str.replace(/(^a-zA-Z )/g,/ \m /);
If not I will just loop over all of them, but I really want to know it it is possible.
Yes. You can give the String.prototype.replace() function a RegExp as it's search. You can also give it a function to handle replacing.
The function will give you the match as the first parameter, and you return what you want to change it to.
const original = 'a1b2c';
const replaced = original.replace(/([^a-z])/gi, match => ` ${match} `);
console.log(replaced);
If you just need to do something simple, you can also just use the $n values ($1, $2, etc) to replace based on the selected group (the sets of parentheses).
const original = 'a1b2c';
const replaced = original.replace(/([^a-z])/gi, ' $1 ');
console.log(replaced);
Yes, it is possible. You can use regex with group:
var text = '2apples!?%$';
var nextText = text.replace(/([^a-zA-Z])/g, ' $1 ');
console.log(nextText);
You can check replace function on this link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

How can I get the last character in a string? [duplicate]

This question already has answers here:
How can I get last characters of a string
(25 answers)
Closed 10 years ago.
If I have the following variable in javascript
var myString = "Test3";
what is the fastest way to parse out the "3" from this string that works in all browsers (back to IE6)
Since in Javascript a string is a char array, you can access the last character by the length of the string.
var lastChar = myString[myString.length -1];
It does it:
myString.substr(-1);
This returns a substring of myString starting at one character from the end: the last character.
This also works:
myString.charAt(myString.length-1);
And this too:
myString.slice(-1);
var myString = "Test3";
alert(myString[myString.length-1])
here is a simple fiddle
http://jsfiddle.net/MZEqD/
Javascript strings have a length property that will tell you the length of the string.
Then all you have to do is use the substr() function to get the last character:
var myString = "Test3";
var lastChar = myString.substr(myString.length - 1);
edit: yes, or use the array notation as the other posts before me have done.
Lots of String functions explained here
myString.substring(str.length,str.length-1)
You should be able to do something like the above - which will get the last character
Use the charAt method. This function accepts one argument: The index of the character.
var lastCHar = myString.charAt(myString.length-1);
You should look at charAt function and take length of the string.
var b = 'I am a JavaScript hacker.';
console.log(b.charAt(b.length-1));

Categories

Resources