Remove certain re-occurring characters from a string - javascript

I am quite new to JS and i have a problem:
I am trying to compare a string (as integer) with an input (as integer). The problem occurs because, the string is written as 10'000'000 for e.g. and the integer as 10000000, with 4 possible scenarios:
- 1'000'000
- 10'000'000
- 100'000'000
- 1'000'000'000
That is, the number (as string) can be from 1 million to 1 billion.
I want to erase (or replace with "") all of my " ' " characters so that the format which i will get for the string will be the same as the one of the integer
E.g. Integer: 95500000 String: 95'500'000 ---> need it to be 95500000
A similar solution but not quite the same is provided here:
Regex remove repeated characters from a string by javascript

String: 95'500'000 ---> need it to be 95500000
That’s as simple as "95'500'000".replace(/'/g, '')
g modifier makes it replace all occurrences, and not just the first one.

const str = "9'0'0000"
const removedSlashStr = str.split('').reduce((removedSlash, char) => {
if(char !== "'") removedSlash+=char
return removedSlash
}, '')
console.log(removedSlashStr) // "900000"

Related

javascript remove a exact index character from the string [duplicate]

This question already has answers here:
Remove a character at a certain position in a string - javascript [duplicate]
(8 answers)
Closed 1 year ago.
let test = 'This is the test string';
console.log(test.substr(3));
console.log(test.slice(3));
console.log(test.substring(3));
Theese methods are removing first 3 character. But i want to remove only third character from the string.
The log has to be: ' Ths is the test string'
Ä°f you help me i will be glad. All examples are giving from the substr, slice eg. eg. Are there any different methods?
First, get the first 3 chars, then add chars 4-end, connect those to get the desired result:
let test = 'This is the test string';
let res = test.substr(0, 2) + test.substr(3);
console.log(res);
Since substr uses the following parameters
substr(start, length)
Start The index of the first character to include in the returned substring.
Length Optional. The number of characters to extract.
If length is omitted, substr() extracts characters to the end of the string.
We can use test.substr(3) to get from the 3'th to the last char without specifying the length of the string
const test = 'This is the test string';
const result = test.slice(0, 2) + test.slice(3);
console.log(result);
You can achieve this by concatenating the two parts of the string, using .slice().
You can achieve it using substring method and concatenating the strings
str = "Delete me ";
function del_one_char(string , removeAt){
return string.substring(0, removeAt) + string.substring( removeAt + 1, string.length);
}
console.log(del_one_char(str , 2))
// result one character at 2nd position is deleted

What value does a substring have if it doesn't exist?

I have a string, msg. I want to check if the third character in the string exists or not.
I've tried if (msg.substring(3, 4) == undefined) { ... } but this doesn't work. What would the substring be equal to if it does not exist?
The third character of the string exists if the string has three characters, so the check you are looking for is
msg.length >= 3
As to your question about a non-existent substring, you get the empty string, which you can test in a console:
> "dog".substring(8, 13)
''
It's generally worth a mention that indexing and taking the length of characters is fraught with Unicode-related difficulties, because what JavaScript thinks of as a character is not really a character, but a UTF-16 character code. So watch out for:
> "😬🤔".length
4
> "😬🤔"[1]
'�'
> "😬🤔"[2]
'�'
> [..."😬🤔"][1]
'🤔'
So if you are looking for better characters do:
[...msg].length >= 3
That will still not work with Unicode grapheme clusters, but it is at least better than taking the actual length of string, which is broken in JavaScript (unless you are dealing with what they call BMP characters).
From the documentation:
Any argument value that is less than 0 or greater than stringName.length is treated as if it were 0 and stringName.length, respectively.
This isn't super intuitive but your example will be an empty string "" (or if the first position has a character and you've added a larger gap, it will be a string that is shorter than the space between indexStart and indexEnd:
const str = 'hi';
console.log(str.substring(1, 4)); // is "i"
You could take a standard property accessor for getting a character or undefined.
const
string0 = '',
string1 = 'a',
string2 = 'ab',
string3 = 'abc',
string4 = 'abcd';
console.log(string0[2]); // undefined
console.log(string1[2]); // undefined
console.log(string2[2]); // undefined
console.log(string3[2]); // c
console.log(string4[2]); // c
If string doesn't contains enough letters substrings doesn't returns nothing. You can try use string as array which return undefined if index doesn't exist.
if ( msg[2] !== undefined ) {}

JavaScript separate currency into number value and currency symbol/name

I am getting a currency value from a web service, that I would like to display in a number input (the float part) and it's currency symbol/name on a simple label that's next to the input.
Example of data that I get from the web service:
$ 1.200,05
R$ 1200.05
kr. 1,200.05
37,200.05 kr.
$300
500.0 €
You can see that the data is very mixed.
The symbol/currency name can be before or after the number value, it can have a space between the symbol and the number, or no space at all. It can also have a dot inside the currency name, that I would still like to keep (like with the danish krone: kr.)
The decimal mark can either be a '.' or a ',' and it can be followed by any number of decimals.
Same with the thousand separator: it can be either a '.' or a ','
I have the following snippet to get the number value, but i'm having trouble getting the currency string part:
if (!isNaN(cost.charAt(0))) { //check whether it starts with number or string, to adjust the regex
var regex = /([+-]?[0-9|^.|^,]+)[\.|,]([0-9])/
var result = regex.exec(cost);
var floatResult = result? result[1].replace(/[.,]/g, "")+ "." + result[2] : cost.replace(/[^0-9-+]/g, "");
return floatResult;
}
else {
var regex = /([+-]?[0-9|^.|^,]+)[\.|,]([0-9]+)$/igm
var result = regex.exec(cost);
var floatResult = result? result[1].replace(/[.,]/g, "")+ "." + result[2] : cost.replace(/[^0-9-+]/g, "");
return floatResult;
}
I am using jQuery and AngularJS in my webapp, so if there's an easier method with the help of one of those, it would be nice.
I'm not sure how to use regex to do this, but what I might do without regex is:
a) record the index of the first numeric character
b) record the index of the last numeric character
c) take the substring from the first to last numeric characters and convert that to a Number, Number(numerics) (you will have to remove commas between numbers for this step)
d) if the first numeric character index is 0, the currency symbol/name will be at the end of the string, after the last numeric character
e) otherwise it will be at the front of the string, before the first numeric character.
edit
you may be able to simplify the whole thing if you can be certain that what you get back as a response always contains one space that seperates the value and the currency symbol. If that were true (as it is in your examples), you could just use string.split(' ') to get an array of the two strings, and check which one is the number.

How can I replace only the last occurence of an number in a string with javascript?

How would you change this:
a-10-b-19-c
into something like this:
a-10-b-20-c
using regular expressions in Javascript?
It should also change this:
a-10-b-19
into this:
a-10-b-20
The only solution I've found so far is:
reverse the original string -> "c-91-b-01-a"
find the first number (with \d+) -> "91"
reverse it -> "19"
turn in into a number (parseInt) -> 19
add 1 to it -> 20
turn it into a string again (toString) -> "20"
reverse it again -> "02"
replace the original match with this new number -> "c-02-b-01-a"
reverse the string -> "a-10-b-20-c"
I was hoping someone on SO would have a simpler way to do this... Anyone?
Here is a simple way.
var str = 'a-10-b-19-c';
str = str.replace(/(\d*)(?=(\D*)?$)/, +str.match(/(\d*)(?=(\D*)?$)/)[0]+1);
+str.match finds 19, adds 1 to it and returns 20. The + makes sure the answer is an int. str.replace finds 19 and replaces it with what str.match returned which was 20.
Explanation
(\d*) - matches any digits
(?=...) - positive lookahead, doesn't change regex position, but makes sure that pattern exists further on down the line.
(\D*)?$ - it doesn't have to, but can match anything that is not a number multiple times and then matches the end of the string
//replaces last digit sequences with 20
'a-10-b-19-c'.replace(/\d+(?!.*\d+)/, '20')
/ --> Start of regex
\d+ --> Match any digit (one or more)
(?!.*\d+) --> negative look ahead assertion that we cannot find any future (one or more) digits
/ --> end of regex
Edit: Just reread about adding,
Can use match for that, e.g.:
var m ='a-10-b-19-c'.match(/\d+(?!.*\d+)/);
'a-10-b-19-c'.replace(/\d+(?!.*\d+)/, parseInt(m[0]) + 1);
Here's an even simpler one:
str.replace(/(.*\D)(\d+)/, function(s, pfx, n) {return pfx + ((+n) + 1)})
or
str.replace(/.*\D(\d+)/, function(s, n) {return s.slice(0, -n.length) + ((+n) + 1)})
Neither of these will work if the number is the first thing in the string, but this one will:
(' ' + str).replace(/.*\D(\d+)/,
function(s, n) {
return s.slice(1, -n.length) + ((+n) + 1)
})
(Why does Javascript need three different substring functions?)
Here's the simplest way I can think of:
var str = 'a-10-b-19-c';
var arr = str.split('-');
arr[3] = parseInt(arr[3]) + 1;
str = arr.join('-');
Edit to explain:
The split() method takes the parameter (in this case the hyphen) and breaks it up into an array at each instance it finds. If you type arr into your JavaScript console after this part runs you'll get ["a", "10", "b", "19", "c"]
We know that we need to change the 4th item here, which is accessed by index 3 via arr[3]. Each piece of this array is a string. If you try to increment a string by 1 it will simply concatenate the string with a 1 (JS uses the + for addition and concatenation) so you need to use parseInt() to make it an integer before you do the addition.
Then we use the join() method to glue the array back together into a string!
Try this one:
var str='a-10-b-19-c';
var pattern=/\d+/g;
var matches=pattern.exec(str);
var last=matches[0];
while((matches=pattern.exec(str))!=null)
{
last=matches[0];
}
var newStr=str.replace(last, parseInt(last)+1);
console.log(newStr);
The code outputs a-10-b-20-c

Can I chain a substring check in javascript?

I am using the following code:
if (store.getItem('TopicID') != "00")
TopidID is always 4 digits and what I need to do is change this to check if the last two digits are "00".
Can I do this as part of the above by just adding ".substring(from, to)" or do I need to put this into a variable and then check the variable?
Use if (!/00$/.test(store.getItem('TopicID')) to check for the last 2 digits not forming '00'. That way the length of the value of store.getItem('TopicID') doesn't matter, you always check for the last two characters of the value, and you don't need the substring 'chaining'.
By the way, I supposed store.getItem('TopicID') returns a String here.
To be complete and in response to Paul Phillips comment: in !/00$/.test([somestring]), /00$/ is a Regular Expression, a special text string for describing a search pattern. In this case it means: for the string resulting from store.getItem('TopicID'), check if you can find 2 consecutive zero's, where the $-sign means 'check for that pattern at the end of the string'.
To be even more complete on the subject of 'chaining': as long as a method is contained by the object to chain, everything can be chained. A completely nonsensical example of that:
Number(/00$/.test('0231')) //convert a boolean to a Number
.toFixed(2) //a Number has the toFixed method
.split('.')[1] //toFixed returns a String, which has method split
.substr(1) //the second element is a string, so substr applies
.concat(' world') //still a string, so concat will do
.split(' ') //string, so split works
.join(' hello ') //from split an array emerged, so join applies
;
//=> result of this chain: '0 hello world'
Can I do this as part of the above by just adding ".substring(from, to)"
Yes, you can. You got the wrong syntax, though.
if (store.getItem('TopicID').substring( 2 ) != "00")
Chaining it would work. So would extracting a local variable. So no, you don't need to. Do it if you think it makes the code more readable.
you can do using slice too
if (store.getItem('TopicID').slice(2,4) != "00") {
// Do Your Stuff
}
Try to use substr or substring with negative start:
if ( store.getItem('TopicID').substr(-2) !== "00" ){...}
or
if ( store.getItem('TopicID').substring(-2) !== "00" ){...}
if it's four digits, you can use
if (store.getItem('TopicID') % 100)
var yourString = (store.getItem('TopicID'))
if(yourString.substring((yourString.length - 2), 2) == "00")
The code above doesn't care how long your string is. It gets the last two digits and compare to "00"

Categories

Resources