how to replace multiple special character in a number? - javascript

I have a number say 2,500.00 and i want to convert the number into 2.500,00. So, we can replace the special character using replace like
var x = 2,500.00;
x.replace(/,/g,".");
and for "Dot" also, we can do it. But in this case, it won't work because when we apply replace function for comma as above, the number will become 2.500.00 and if we apply now, it will become as 2,500,00.
So is there any way to convert 2,500.00 into 2.500,00 ?

String.prototype.replace can take a function:
'2,123,500.00'.replace(/[,.]/g, function(c){ return c===',' ? '.' : ','; });

You can use:
var x = '2,123,500.00';
var arr = x.split('.');
var y = arr[0].replace(/,/g, '.') + ',' + arr[1];
//=> 2.123.500,00

You're in luck, .replace() accept a function as second argument. That function has the matched string as argument and the returned value will be the replace_by value of .replace().
In short, you can simply check what the matched string is and return the right value :
var str = "2,500.00";
var changed_str = str.replace(/,|\./g, function(old){
if (old === '.')
return ',';
else if (old === ',')
return '.';
});
document.write(changed_str)

Why not use the built-in methods to format your numbers correctly?
Number.toLocaleString() would work just fine here.
If you actually have a number as you said, you can easily achieve this using the right locale. If you have a String representation of your number, you would first have to parse it.

This (now) works for any number of commas or dots, even if trailing or leading dots or commas.
HTML:
<div id="result"></div>
JS:
var x = '.,2.123,50.0.00.';
var between_dots = x.split('.');
for (var i = 0; i < between_dots.length; i++) {
between_dots[i] = between_dots[i].replace(/,/g, '.');
}
var y = between_dots.join(',');
document.getElementById('result').innerHTML = y;
Here's the JSFiddle

Related

Editing a string using regex jquery [duplicate]

i have comma separated string like
var test = 1,3,4,5,6,
i want to remove particular character from this string using java script
can anyone suggests me?
JavaScript strings provide you with replace method which takes as a parameter a string of which the first instance is replaced or a RegEx, which if being global, replaces all instances.
Example:
var str = 'aba';
str.replace('a', ''); // results in 'ba'
str.replace(/a/g, ''); // results in 'b'
If you alert str - you will get back the same original string cause strings are immutable.
You will need to assign it back to the string :
str = str.replace('a', '');
Use replace and if you want to remove multiple occurrence of the character use
replace like this
var test = "1,3,4,5,6,";
var newTest = test.replace(/,/g, '-');
here newTest will became "1-3-4-5-6-"
you can make use of JavaScript replace() Method
var str="Visit Microsoft!";
var n=str.replace("Microsoft","My Blog");
var test = '1,3,4,5,6';​​
//to remove character
document.write(test.replace(/,/g, ''));
//to remove number
function removeNum(string, val){
var arr = string.split(',');
for(var i in arr){
if(arr[i] == val){
arr.splice(i, 1);
i--;
}
}
return arr.join(',');
}
var str = removeNum(test,3);
document.write(str); // output 1,4,5,6
You can also
var test1 = test.split(',');
delete test1[2];
var test2 = test1.toString();
Have fun :)
you can split the string by comma into an array and then remove the particular element [character or number or even string] from that array. once the element(s) removed, you can join the elements in the array into a string again
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
You can use this function
function removeComma(inputNumber,char='') {
return inputNumber.replace(/,/g, char);
}
Update
function removeComma(inputNumber) {
inputNumber = inputNumber.toString();
return Number(inputNumber.replace(/,/g, ''));
}

Javascript calculation giving wrong answer because of comma

I have a calculation which works fine until it hits a thousand separator, which is a comma. I have tried a few things trying to get rid of the comma but I can't seem to get it right. Below is the last thing I tried which was a total failure. The 'tot_amount' is the one I need the comma stripped from. I think I went down the wrong track and it should be doable without the extra 'tot' variable. Please assist.
function updateDue() {
var total = parseInt(document.getElementById("tot_amount").value);
var val2 = parseInt(document.getElementById("eftposamount").value);
var tot = total.replace(",","");
// to make sure that they are numbers
if (!tot) { tot = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = tot - val2;
}
Replacing
Your code is only removing one comma, try using this instead:
total.replace(/,/g, "");
The best way is to remove all non-number safe stuff and use that:
+total.replace(/[^\de.-]/gi, "")
As you see I've a g
The g stands for global meaning it will replace all commas instead of just the first one.
String to Integers
Instead of:
var total = parseInt(document.getElementById("tot_amount").value);
var tot = total.replace(",","");
You must make it an integer after you parse it. A short way to parse a number is using +
var total = +document.getElementById("tot_amount").value.replace(/[^\de.-]/gi, "")
Your code:
You can make your function this:
function updateDue() {
document.getElementById("remainingval").value =
+document.getElementById("tot_amount").value.replace(/[^\de.-]/gi, "") -
+document.getElementById("eftposamount").value.replace(/[^\de.-]/gi, "")
|| 0
}
The ||0 will remove the need for the ifs.
Calling parseInt on a comma-delimited string will give you unexpected results:
parseInt('1,000'); // => 1
Instead, you want to remove commas, and then parse the integer:
var i = +('1,000'.replace(/,/g, '')); // => 1000
The // part is simply RegExp notation, and the g afterwards is a flag that tells the parser to look for global instances of the expression. In your case, you want to remove all commas, so the g flag is appropriate.
For the sake of saving 7 characters in your code, you can simply coerce your value to an integer with + rather than calling parseInt.

How to grab string(s) before the second " - "?

var string = "bs-00-xyz";
As soon as the second dash has detected, I want to grab whatever before that second dash, which is bs-00 in this case.
I am not sure what is the most efficient way to do that, and here is what I come up with.
JSFiddle = http://jsfiddle.net/bheng/tm3pr1h9/
HTML
<input id="searchbox" placeholder="Enter SKU or name to check availability " type="text" />
JS
$("#searchbox").keyup(function() {
var query = this.value;
var count = (query.match(/-/g) || []).length;
if( count == 2 ){
var results = query.split('-');
var new_results = results.join('-')
alert( "Value before the seond - is : " + new_results );
}
});
You could do it without regex with this
myString.split('-').splice(0, 2).join('-');
In case there are more than two dashes in your string...
var myString = string.substr(0, string.indexOf('-', string.indexOf('-') + 1));
Using a regular expression match:
var string = "bs-00-xyz";
newstring = string.match(/([^-]+-[^-]+)-/i);
// newstring = "bs-00"
This will work for strings with more than two dashes as well.
Example:
var string = "bs-00-xyz-asdf-asd";
I think splitting on character is a fine approach, but just for variety's sake...you could use a regular expression.
var match = yourString.match(/^([^\-]*\-[^\-]*)\-/);
That expression would return the string you're looking for as match[1] (or null if no such string could be found).
you need use lastIndexOf jsfiddle, check this example
link update...

Delete first character of string if it is 0

I want to delete the first character of a string, if the first character is a 0. The 0 can be there more than once.
Is there a simple function that checks the first character and deletes it if it is 0?
Right now, I'm trying it with the JS slice() function but it is very awkward.
You can remove the first character of a string using substring:
var s1 = "foobar";
var s2 = s1.substring(1);
alert(s2); // shows "oobar"
To remove all 0's at the start of the string:
var s = "0000test";
while(s.charAt(0) === '0')
{
s = s.substring(1);
}
Very readable code is to use .substring() with a start set to index of the second character (1) (first character has index 0). Second parameter of the .substring() method is actually optional, so you don't even need to call .length()...
TL;DR : Remove first character from the string:
str = str.substring(1);
...yes it is that simple...
Removing some particular character(s):
As #Shaded suggested, just loop this while first character of your string is the "unwanted" character...
var yourString = "0000test";
var unwantedCharacter = "0";
//there is really no need for === check, since we use String's charAt()
while( yourString.charAt(0) == unwantedCharacter ) yourString = yourString.substring(1);
//yourString now contains "test"
.slice() vs .substring() vs .substr()
EDIT: substr() is not standardized and should not be used for new JS codes, you may be inclined to use it because of the naming similarity with other languages, e.g. PHP, but even in PHP you should probably use mb_substr() to be safe in modern world :)
Quote from (and more on that in) What is the difference between String.slice and String.substring?
He also points out that if the parameters to slice are negative, they
reference the string from the end. Substring and substr doesn´t.
Use .charAt() and .slice().
Example: http://jsfiddle.net/kCpNQ/
var myString = "0String";
if( myString.charAt( 0 ) === '0' )
myString = myString.slice( 1 );
If there could be several 0 characters at the beginning, you can change the if() to a while().
Example: http://jsfiddle.net/kCpNQ/1/
var myString = "0000String";
while( myString.charAt( 0 ) === '0' )
myString = myString.slice( 1 );
The easiest way to strip all leading 0s is:
var s = "00test";
s = s.replace(/^0+/, "");
If just stripping a single leading 0 character, as the question implies, you could use
s = s.replace(/^0/, "");
You can do it with substring method:
let a = "My test string";
a = a.substring(1);
console.log(a); // y test string
Did you try the substring function?
string = string.indexOf(0) == '0' ? string.substring(1) : string;
Here's a reference - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring
And you can always do this for multiple 0s:
while(string.indexOf(0) == '0')
{
string = string.substring(1);
}
One simple solution is to use the Javascript slice() method, and pass 1 as a parameter
let str = "khattak01"
let resStr = str.slice(1)
console.log(resStr)
Result : hattak01
var s = "0test";
if(s.substr(0,1) == "0") {
s = s.substr(1);
}
For all 0s: http://jsfiddle.net/An4MY/
String.prototype.ltrim0 = function() {
return this.replace(/^[0]+/,"");
}
var s = "0000test".ltrim0();
const string = '0My string';
const result = string.substring(1);
console.log(result);
You can use the substring() javascript function.
//---- remove first and last char of str
str = str.substring(1,((keyw.length)-1));
//---- remove only first char
str = str.substring(1,(keyw.length));
//---- remove only last char
str = str.substring(0,(keyw.length));
try
s.replace(/^0/,'')
console.log("0string =>", "0string".replace(/^0/,'') );
console.log("00string =>", "00string".replace(/^0/,'') );
console.log("string00 =>", "string00".replace(/^0/,'') );
Here's one that doesn't assume the input is a string, uses substring, and comes with a couple of unit tests:
var cutOutZero = function(value) {
if (value.length && value.length > 0 && value[0] === '0') {
return value.substring(1);
}
return value;
};
http://jsfiddle.net/TRU66/1/
String.prototype.trimStartWhile = function(predicate) {
if (typeof predicate !== "function") {
return this;
}
let len = this.length;
if (len === 0) {
return this;
}
let s = this, i = 0;
while (i < len && predicate(s[i])) {
i++;
}
return s.substr(i)
}
let str = "0000000000ABC",
r = str.trimStartWhile(c => c === '0');
console.log(r);
Another alternative to get the first character after deleting it:
// Example string
let string = 'Example';
// Getting the first character and updtated string
[character, string] = [string[0], string.substr(1)];
console.log(character);
// 'E'
console.log(string);
// 'xample'
From the Javascript implementation of trim() > that removes and leading or ending spaces from strings. Here is an altered implementation of the answer for this question.
var str = "0000one two three0000"; //TEST
str = str.replace(/^\s+|\s+$/g,'0'); //ANSWER
Original implementation for this on JS
string.trim():
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,'');
}
}
Another alternative answer
str.replace(/^0+/, '')
var test = '0test';
test = test.replace(/0(.*)/, '$1');

Separate character and number in javascript

I have one string which contain number and character. I need to separate number and character. I have don't have a delimiter in between. How can I do this.
Var selectedRow = "E0";
I need to "0" in another variable.
Help me on this.
Depends on the format of the selected row, if it is always the format 1char1number (E0,E1....E34) then you can do:
var row = "E0";
var rowChar = row.substring(0, 1);
// Number var is string format, use parseInt() if you need to do any maths on it
var number = row.substring(1, row.length);
//var number = parseInt(row.substring(1, row.length));
If however you can have more than 1 character, for example (E0,E34,EC5,EDD123) then you can use regular expressions to match the numeric and alpha parts of the string, or loop each character in the string.
var m = /\D+(\d+)/gi.exec(selectedRow);
var row = m.length == 2 ? m[1] : -1;
selectedRow.charAt(1)
Becomes more complex if your example is something longer than 'E0', obviously.

Categories