replace commas with dots and add element to string - javascript

I want to replace all commas of a (number) string with dots and add another element at the same time to display the currency
so far I have this
$("#myelement").text(function () {
return $(this).text().replace(/\,/g, '.');
});
So far this works and returns for example 1,234,567 as 1.234.567 but how can I add a string/element to it so that I get 1.234.567 Dollars or 1.234.567 Rupis etc.

Just add + " Dollars" (or Rupees, etc.) to what you're returning from the function:
$("#myelement").text(function () {
return $(this).text().replace(/\,/g, '.') + " Dollars";
});
Note that as georg points out, you don't need the $(this).text() part, the callback gets the index and the old text as arguments:
$("#myelement").text(function(index, text) {
return text.replace(/\,/g, '.') + " Dollars";
});
Side note: , isn't special in regular expressions, no need to escape it (although doing so is harmless). So just /,/g, not /\,/g.

Related

javascript collapsing many spaces into one, like HTML? strange behavior

I'm encountering this weird behaviour and I don't really understand why.
I have a function to normalize strings:
function normalize_for_find(name) {
return name
.trim()
.replace(/&/g, '&')
.replace(/ /g, ' ');
}
Which if I execute in chrome console, I get " " transformed into two spaces, which is what I want:
normalize_for_find("MONKEY BISCUITS 200g")
"MONKEY BISCUITS 200g"
But then when I use it in this method, it somehow transforms " " into only one space.
function find_by_name(elems, name) {
name = normalize_for_find(name);
return _.find(elems, function(e) {
return name === normalize_for_find(e.name);
});
}
Take a look at this debugging:
name starts as "MONKEY BISCUITS 200g"
and then after the call to normalize_for_find it appears as "MONKEY BISCUITS 200g" (only one space)
I need it to be two spaces like when I execute from console.
Here is more info on watching each variable, which makes no sense to me at all!
The difference between both strings is that the original e.name contains a "non breaking space" char which is ascii code 160, while the normalize_for_find method inserts a regular space which is ascii code 32.
As suggested by another user, this can also be fixed by changing the normalize method to this:
function normalize_for_find(name) {
var parsed = jQuery.parseHTML(name);
if (!parsed || parsed.length == 0) return '';
return parsed[0].data.trim();
}
(note that jQuery.parseHTML(name) will return null for '')

Javascript - How to use variable separator for split function?

I have some function that uses split, but I want the separator to be a variable. separator will be used several places and it would be nice to only have to change the variable once rather than change hard code everywhere.
But, of course, it doesn't work. The pattern looks correct, but split must have some problem with variables defining the split.
Here is some testing I did in Google Chrome's console.
separator = '|'; // separator to use
var pattern = '/\\' + separator + '\\s*/'; // define pattern
undefined
pattern;
"/\|\s*/"
// pattern is correct
// now define function with constant... variable version commented:
function split( val ) {
//var pattern = '/\\' + separator + '\\s*/';
return val.split( /\|\s*/ );
//return val.split( pattern );
}
undefined
split('asdf|jkl');
["asdf", "jkl"]
// function worked as expected
// now uncomment the variable portions:
function split( val ) {
var pattern = '/\\' + separator + '\\s*/';
//return val.split( /\|\s*/ );
return val.split( pattern );
}
undefined
split('asdf|jkl');
["asdf|jkl"]
// not as expected. string is not split into array
I assume this has something to do with the split function. How do I get this to work? Note that the only reason I think I need to do it this way is because I want to easily be able to change separator. If not for that, I could just hard code everything it would work.
EDIT:
I don't care if it uses regex or not. But it needs to split the string on separator and also make sure the values are trimmed of extra spaces.
Also, I'm modeling my code after the jQuery UI page for autocomplete, here.
And here's the function as they have it. I don't know why they define their own split.
function split( val ) {
return val.split( /,\s*/ );
}
Concat the string, and use it to create an instance of a new RegExp obj.
function split( val ) {
var pattern = new RegExp('\\' + separator + '\\s*');
return val.split( pattern );
}
EDITS
Note that in this particular example, there doesn't appear to be any value over String.prototype.split().
This would be more useful if you wanted to set a limit for all splits of a certain type:
function split( val ) {
var pattern = new RegExp('\\' + separator + '\\s*');
return val.split( pattern , 3);
}
without having to write:
strVar.split(pattern, 3);
Yes, that limit can be stored as a variable and referenced, but then you have to expose that variable throughout the scope of every function you want to use it in.
What if you wanted to change it so it would take an array of strings to split, instead?
You can split on a string or on a regular expression,
but don't mix them up-
var separator='|', val='Split | on | the | pipes';
val.split(RegExp('\\' + separator + '\\s*')).join('\n');
/* returned value: (String)
Split
on
the
pipes
*/
Please use split() and don't have a hard time making your own function
http://www.w3schools.com/jsref/jsref_split.asp
A quick example
<p id="demo">Click the button to display the array values after the split.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str="How are you doing today?";
var n=str.split(" ");
document.getElementById("demo").innerHTML=n;
}
</script>
then just put the pattern on the split() parameter. make sure escape any character you will put on the parameter because the split() thinks you entered a regex. Your | separator is a regex special character and you must escape it with a backslash
Best way is to just use String.split as it can split by using strings itself.
But as you wish to explore RegEx, you need to ensure the separator is correctly escaped before attempting the split:
Here is a working function where separator can be any string:
function split(val, separator) {
var separator = separator.replace(/([^\w\s])/g, '\\$1');
return val.split(new RegExp(separator));
}
split("String|$Array|$Objects", "|$");
> Result ["String", "Array", "Objects"]

How can I remove a character from a string using JavaScript?

I am so close to getting this, but it just isn't right.
All I would like to do is remove the character r from a string.
The problem is, there is more than one instance of r in the string.
However, it is always the character at index 4 (so the 5th character).
Example string: crt/r2002_2
What I want: crt/2002_2
This replace function removes both r
mystring.replace(/r/g, '')
Produces: ct/2002_2
I tried this function:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
}
mystring.replaceAt(4, '')
It only works if I replace it with another character. It will not simply remove it.
Any thoughts?
var mystring = "crt/r2002_2";
mystring = mystring.replace('/r','/');
will replace /r with / using String.prototype.replace.
Alternatively you could use regex with a global flag (as suggested by Erik Reppen & Sagar Gala, below) to replace all occurrences with
mystring = mystring.replace(/\/r/g, '/');
EDIT:
Since everyone's having so much fun here and user1293504 doesn't seem to be coming back any time soon to answer clarifying questions, here's a method to remove the Nth character from a string:
String.prototype.removeCharAt = function (i) {
var tmp = this.split(''); // convert to an array
tmp.splice(i - 1 , 1); // remove 1 element from the array (adjusting for non-zero-indexed counts)
return tmp.join(''); // reconstruct the string
}
console.log("crt/r2002_2".removeCharAt(4));
Since user1293504 used the normal count instead of a zero-indexed count, we've got to remove 1 from the index, if you wish to use this to replicate how charAt works do not subtract 1 from the index on the 3rd line and use tmp.splice(i, 1) instead.
A simple functional javascript way would be
mystring = mystring.split('/r').join('/')
simple, fast, it replace globally and no need for functions or prototypes
There's always the string functions, if you know you're always going to remove the fourth character:
str.slice(0, 4) + str.slice(5, str.length)
Your first func is almost right. Just remove the 'g' flag which stands for 'global' (edit) and give it some context to spot the second 'r'.
Edit: didn't see it was the second 'r' before so added the '/'. Needs \/ to escape the '/' when using a regEx arg. Thanks for the upvotes but I was wrong so I'll fix and add more detail for people interested in understanding the basics of regEx better but this would work:
mystring.replace(/\/r/, '/')
Now for the excessive explanation:
When reading/writing a regEx pattern think in terms of: <a character or set of charcters> followed by <a character or set of charcters> followed by <...
In regEx <a character or set of charcters> could be one at a time:
/each char in this pattern/
So read as e, followed by a, followed by c, etc...
Or a single <a character or set of charcters> could be characters described by a character class:
/[123!y]/
//any one of these
/[^123!y]/
//anything but one of the chars following '^' (very useful/performance enhancing btw)
Or expanded on to match a quantity of characters (but still best to think of as a single element in terms of the sequential pattern):
/a{2}/
//precisely two 'a' chars - matches identically as /aa/ would
/[aA]{1,3}/
//1-3 matches of 'a' or 'A'
/[a-zA-Z]+/
//one or more matches of any letter in the alphabet upper and lower
//'-' denotes a sequence in a character class
/[0-9]*/
//0 to any number of matches of any decimal character (/\d*/ would also work)
So smoosh a bunch together:
var rePattern = /[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/g
var joesStr = 'aaaAAAaaEat at Joes123454321 or maybe aAaAJoes all you can eat098765';
joesStr.match(rePattern);
//returns ["aaaAAAaaEat at Joes123454321", "aAaAJoes all you can eat0"]
//without the 'g' after the closing '/' it would just stop at the first match and return:
//["aaaAAAaaEat at Joes123454321"]
And of course I've over-elaborated but my point was simply that this:
/cat/
is a series of 3 pattern elements (a thing followed by a thing followed by a thing).
And so is this:
/[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/
As wacky as regEx starts to look, it all breaks down to series of things (potentially multi-character things) following each other sequentially. Kind of a basic point but one that took me a while to get past so I've gone overboard explaining it here as I think it's one that would help the OP and others new to regEx understand what's going on. The key to reading/writing regEx is breaking it down into those pieces.
Just fix your replaceAt:
String.prototype.replaceAt = function(index, charcount) {
return this.substr(0, index) + this.substr(index + charcount);
}
mystring.replaceAt(4, 1);
I'd call it removeAt instead. :)
For global replacement of '/r', this code worked for me.
mystring = mystring.replace(/\/r/g,'');
This is improvement of simpleigh answer (omit length)
s.slice(0, 4) + s.slice(5)
let s = "crt/r2002_2";
let o = s.slice(0, 4) + s.slice(5);
let delAtIdx = (s, i) => s.slice(0, i) + s.slice(i + 1); // this function remove letter at index i
console.log(o);
console.log(delAtIdx(s, 4));
let str = '1234567';
let index = 3;
str = str.substring(0, index) + str.substring(index + 1);
console.log(str) // 123567 - number "4" under index "3" is removed
return this.substr(0, index) + char + this.substr(index + char.length);
char.length is zero. You need to add 1 in this case in order to skip character.
Maybe I'm a noob, but I came across these today and they all seem unnecessarily complicated.
Here's a simpler (to me) approach to removing whatever you want from a string.
function removeForbiddenCharacters(input) {
let forbiddenChars = ['/', '?', '&','=','.','"']
for (let char of forbiddenChars){
input = input.split(char).join('');
}
return input
}
Create function like below
String.prototype.replaceAt = function (index, char) {
if(char=='') {
return this.slice(0,index)+this.substr(index+1 + char.length);
} else {
return this.substr(0, index) + char + this.substr(index + char.length);
}
}
To replace give character like below
var a="12346";
a.replaceAt(4,'5');
and to remove character at definite index, give second parameter as empty string
a.replaceAt(4,'');
If it is always the 4th char in yourString you can try:
yourString.replace(/^(.{4})(r)/, function($1, $2) { return $2; });
It only works if I replace it with another character. It will not simply remove it.
This is because when char is equal to "", char.length is 0, so your substrings combine to form the original string. Going with your code attempt, the following will work:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + 1);
// this will 'replace' the character at index with char ^
}
DEMO
You can use this: if ( str[4] === 'r' ) str = str.slice(0, 4) + str.slice(5)
Explanation:
if ( str[4] === 'r' )
Check if the 5th character is a 'r'
str.slice(0, 4)
Slice the string to get everything before the 'r'
+ str.slice(5)
Add the rest of the string.
Minified: s=s[4]=='r'?s.slice(0,4)+s.slice(5):s [37 bytes!]
DEMO:
function remove5thR (s) {
s=s[4]=='r'?s.slice(0,4)+s.slice(5):s;
console.log(s); // log output
}
remove5thR('crt/r2002_2') // > 'crt/2002_2'
remove5thR('crt|r2002_2') // > 'crt|2002_2'
remove5thR('rrrrr') // > 'rrrr'
remove5thR('RRRRR') // > 'RRRRR' (no change)
If you just want to remove single character and
If you know index of a character you want to remove, you can use following function:
/**
* Remove single character at particular index from string
* #param {*} index index of character you want to remove
* #param {*} str string from which character should be removed
*/
function removeCharAtIndex(index, str) {
var maxIndex=index==0?0:index;
return str.substring(0, maxIndex) + str.substring(index, str.length)
}
I dislike using replace function to remove characters from string. This is not logical to do it like that. Usually I program in C# (Sharp), and whenever I want to remove characters from string, I use the Remove method of the String class, but no Replace method, even though it exists, because when I am about to remove, I remove, no replace. This is logical!
In Javascript, there is no remove function for string, but there is substr function. You can use the substr function once or twice to remove characters from string. You can make the following function to remove characters at start index to the end of string, just like the c# method first overload String.Remove(int startIndex):
function Remove(str, startIndex) {
return str.substr(0, startIndex);
}
and/or you also can make the following function to remove characters at start index and count, just like the c# method second overload String.Remove(int startIndex, int count):
function Remove(str, startIndex, count) {
return str.substr(0, startIndex) + str.substr(startIndex + count);
}
and then you can use these two functions or one of them for your needs!
Example:
alert(Remove("crt/r2002_2", 4, 1));
Output: crt/2002_2
Achieving goals by doing techniques with no logic might cause confusions in understanding of the code, and future mistakes, if you do this a lot in a large project!
The following function worked best for my case:
public static cut(value: string, cutStart: number, cutEnd: number): string {
return value.substring(0, cutStart) + value.substring(cutEnd + 1, value.length);
}
The shortest way would be to use splice
var inputString = "abc";
// convert to array and remove 1 element at position 4 and save directly to the array itself
let result = inputString.split("").splice(3, 1).join();
console.log(result);
This problem has many applications. Tweaking #simpleigh solution to make it more copy/paste friendly:
function removeAt( str1, idx) {
return str1.substr(0, idx) + str1.substr(idx+1)
}
console.log(removeAt('abbcdef', 1)) // prints: abcdef
Using [index] position for removing a specific char (s)
String.prototype.remplaceAt = function (index, distance) {
return this.slice(0, index) + this.slice(index + distance, this.length);
};
credit to https://stackoverflow.com/users/62576/ken-white
So basically, another way would be to:
Convert the string to an array using Array.from() method.
Loop through the array and delete all r letters except for the one with index 1.
Convert array back to a string.
let arr = Array.from("crt/r2002_2");
arr.forEach((letter, i) => { if(letter === 'r' && i !== 1) arr[i] = "" });
document.write(arr.join(""));
In C# (Sharp), you can make an empty character as '\0'.
Maybe you can do this:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
}
mystring.replaceAt(4, '\0')
Search on google or surf on the interent and check if javascript allows you to make empty characters, like C# does. If yes, then learn how to do it, and maybe the replaceAt function will work at last, and you'll achieve what you want!
Finally that 'r' character will be removed!

Cross-Browser Regular expression library for Javascript to replace using function

Is there a library for replacing using functions as argument
when I call this function
"foo[10]bar[20]baz".replacef(/\[([0-9]*)\]/g, function(a) {
return '[' + (ParseInt(a)*10) + ']';
});
it should return
"foo[20]bar[30]baz";
and when I call with this
"foo[10;5]bar[15;5]baz".replacef(/\[([0-9]*);([0-9]*)\]/g, function(a, b) {
return '_' + (ParseInt(a)+ParseInt(b)) + '_';
});
it should return
"foo_15_bar_20_baz"
Is there existing Cross-Browser library that have function like this or similar in JavaScript?
That's how the "replace()" function already works. If the second parameter is a function, it's passed a list of arguments that are pretty much the same as the array returned from the RegExp "exec()" function. The function returns what it wants the matched region to be replaced with.
The first argument to the called function is the whole matched string. The second and subsequent arguments are the captured groups from the regex (like your second example). Your second example, however, would need a function with one more parameter to hold the entire matched string.
Example:
var s = "hello world".replace(/(\w+)\s*(\w+)/, function(wholeMatch, firstWord, secondWord) {
return "first: " + firstWord + " second: " + secondWord;
});
alert(s); // "first: hello second: world"
As far as I know you can readily do something like this in javascript :
"foo[10]bar[20]baz".replace(/\[([0-9]+)\]/g, function() {
return '[' + (parseInt(arguments[1])*10) + ']';
});
This is afaik cross browser (notice that parseInt got no leading uppercase p), arguments contains the match, index 0 is the whole thing, 1 and so on are the captured groups.

Javascript regexp: replacing $1 with f($1)

I have a regular expression, say /url.com\/([A-Za-z]+)\.html/, and I would like to replace it with new string $1: f($1), that is, with a constant string with two interpolations, the captured string and a function of the captured string.
What's the best way to do this in JavaScript? 'Best' here means some combination of (1) least error-prone, (2) most efficient in terms of space and speed, and (3) most idiomatically appropriate for JavaScript, with a particular emphasis on #3.
The replace method can take a function as the replacement parameter.
For example:
str.replace(/regex/, function(match, group1, group2, index, original) {
return "new string " + group1 + ": " + f(group1);
});
When using String.replace, you can supply a callback function as the replacement parameter instead of a string and create your own, very custom return value.
'foo'.replace(/bar/, function (str, p1, p2) {
return /* some custom string */;
});
.replace() takes a function for the replace, like this:
var newStr = string.replace(/url.com\/([A-Za-z]+)\.html/, function(all, match) {
return match + " something";
});
You can transform the result however you want, just return whatever you want the match to be in that callback. You can test it out here.

Categories