Separate character and number in javascript - 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.

Related

How to parse string value "(20)" to Integer in Javascript?

I'm working with a string "(20)". I need to convert it to an int. I read parseInt is a function which helps me to achieve that, but i don't know how.
Use string slicing and parseInt()
var str = "(20)"
str = str.slice(1, -1) // remove parenthesis
var integer = parseInt(str) // make it an integer
console.log(integer) // 20
One Line version
var integer = parseInt("(20)".slice(1, -1))
The slice method slices the string by the start and end index, start is 1, because that’s the (, end is -1, which means the last one - ), therefore the () will be stripped. Then parseInt() turns it into an integer.
Or use regex so it can work with other cases, credits to #adeithe
var integer = parseInt("(20)".match(/\d+/g))
It will match the digits and make it an integer
Read more:
slicing strings
regex
You can use regex to achieve this
var str = "(20)"
parseInt(str.match(/\d+/g).join())
Easy, use this
var number = parseInt((string).substr(2,3));
You need to extract that number first, you can use the match method and a regex \d wich means "digits". Then you can parse that number
let str = "(20)";
console.log(parseInt(str.match(/\d+/)));
Cleaner version of Hedy's
var str = "(20)";
var str_as_integer = parseInt(str.slice(1, -1))

I need help getting the first n characters of a string up to when a number character starts

I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.
Not sure how to do this with regex my limited knowledge is blocking me at this point:
^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring
Using \w will match a word character which includes characters and digits and an underscore.
You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z
^[0-9]?[A-Za-z]+
Regex demo
const regex = /^[0-9]?[A-Za-z]+/;
[
"7EUSA8889er898",
"somelongstring292894830982",
"SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));
Can use this regex code:
(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)
I try with exmaple and good worked:
1- somelongstring292894830982 -> somelongstring
2- 7sdfsdf5456 -> 7sdfsdf
3- 875werwer54556 -> 875werwer
If you want to create function where the RegExp is parametrized by n parameter, this would be
function getStr(str,n) {
var pattern = "\\d?\\w{0,"+n+"}";
var reg = new RegExp(pattern);
var result = reg.exec(str);
if(result[0]) return result[0].substr(0,n);
}
There are answers to this but here is another way to do it.
var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';
var Extract = function (args) {
var C = args.split(''); // Split string in array
var NI = []; // Store indexes of all numbers
// Loop through list -> if char is a number add its index
C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
// Get the items between the first and second occurence of a number
return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));
Output
EUSA
SWFX7
Since it's hard to tell what you are trying to match, I'd go with a general regex
^\d?\D+(?=\d)

Javascript string replace certain characters

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];
}

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.

split string based on a symbol

I'm trying to split a string into an array based on the second occurrence of the symbol _
var string = "this_is_my_string";
I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.
In the example string above I would need it to be split like this.
var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
string.substring(secondUnderscore)];
Paste it into your browser's console to try it out. No need for a jsFiddle.
var string = "this_is_my_string";
var splitChar = string.indexOf('_', string.indexOf('_') + 1);
var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];
This should work.
var str = "this_is_my_string";
var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE
var firstPart = matches[1]; // this_is
var secondPart = matches[2]; // _my_string
This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?), says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.
I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:
String str = "this_is_my_string";
String undScore1 = str.split("_")[0];
String undScore2 = str.split("_")[1];
String bothUndScores = undScore1 + "_" + undScore2 + "_";
String allElse = str.split(bothUndScores)[1];
System.out.println(allElse);
This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.

Categories