How to extract last digit from string which contains chars and numbers - javascript

How can i extract from string only last number which should be "5"?
var str = "1000040928423195 points added to your balance";
var str = parseInt(str);
var lastNum = str.substr(str.length - 1);
console.log(lastNum);

Given your string...
var str = "1000040928423195 points added to your balance";
... we can extract all the numbers with a regex...
var onlyNumbers = str.replace(/\D/g,'');
... and, finally, get the last one:
var lastNumber = onlyNumbers.substring(onlyNumbers.length - 1);
Here is a demo:
var str = "1000040928423195 points added to your balance";
var onlyNumbers = str.replace(/\D/g,'');
var lastNumber = onlyNumbers.substring(onlyNumbers.length - 1);
console.log(lastNumber);

Just add toString() after parseInt
var str = "1000040928423195 points added to your balance";
var str = parseInt(str).toString();
var lastNum = str.substr(str.length - 1);
console.log(lastNum);

Use a regex like /\d+(\d)/
var str = "1000040928423195 points added to your balance";
str.match(/\d+(\d)/)[1]

After your second line, str isn't a string any more; it is an integer. As such, you can extract the last digit with str % 10; if necessary, convert that to a string.

Try parsing it with a Regular Expression like so :)
string = "120394023954932503 fdsaf fdsaf dasfasd";
regex = /([0-9]*)/g;
match = regex.exec(string);
last_num = match[0].substr(match[0].length - 1);
console.log(last_num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="string_val"></div>

Use the regex \d+(\d) to match multiple digits followed by a digit.
\d will occupy as many as possible, where (\d) will match the last.
Then get the last number from the first group [1].
var str = "1000040928423195 points added to your balance";
var match = /\d+(\d)/g.exec(str)[1];
console.log(match);

var digit = /.*(\d)/.exec("awoo123awoo")[1];
3

Related

How can I replace single digit numbers within a string without affecting 2 digit numbers in that string

I'm working to update this function which currently takes the content and replaces any instance of the target with the substitute.
var content = textArea.value; //should be in string form
var target = targetTextArea.value;
var substitute = substituteTextArea.value;
var expression = new RegExp(target, "g"); //In order to do a global replace(replace more than once) we have to use a regex
content = content.replace(expression, substitute);
textArea.value = content.split(",");
This code somewhat works... given the input "12,34,23,13,22,1,17" and told to replace "1" with "99" the output would be "992,34,23,993,22,99,997" when it should be "12,34,23,13,22,99,17". The replace should only be performed when the substitute is equal to the number, not a substring of the number.
I dont understand the comment about the regex needed to do a global replace, I'm not sure if that's a clue?
It's also worth mentioning that I'm dealing with a string separated by either commas or spaces.
Thanks!
You could do this if regex is not a requirement
var str = "12,34,23,13,22,1,17";
var strArray = str.split(",");
for(var item in strArray)
{
if(strArray[item] === "1")
{
strArray[item] = "99"
}
}
var finalStr = strArray.join()
finalStr will be "12,34,23,13,22,99,17"
Try with this
var string1 = "12,34,23,13,22,1,17";
var pattern = /1[^\d]/g;
// or pattern = new RegExp(target+'[^\\d]', 'g');
var value = substitute+",";//Replace comma with space if u uses space in between
string1 = string1.replace(pattern, value);
console.log(string1);
Try this
target = target.replace(/,1,/g, ',99,');
Documentation
EDIT: When you say: "a string separated by either commas or spaces"
Do you mean either a string with all commas, or a string with all spaces?
Or do you have 1 string with both commas and spaces?
My answer has no regex, nothing fancy ...
But it looks like you haven't got an answer that works yet
<div id="log"></div>
<script>
var myString = "12,34,23,13,22,1,17";
var myString2 = "12 34 23 13 22 1 17";
document.getElementById('log').innerHTML += '<br/>with commas: ' + replaceItem(myString, 1, 99);
document.getElementById('log').innerHTML += '<br/>with spaces: ' + replaceItem(myString2, 1, 99);
function replaceItem(string, needle, replace_by) {
var deliminator = ',';
// split the string into an array of items
var items = string.split(',');
// >> I'm dealing with a string separated by either commas or spaces
// so if split had no effect (no commas found), we try again with spaces
if(! (items.length > 1)) {
deliminator = ' ';
items = string.split(' ');
}
for(var i=0; i<items.length; i++) {
if(items[i] == needle) {
items[i] = replace_by;
}
}
return items.join(deliminator);
}
</script>

How to cut third symbol from string and alert it without third symbol

How can i correctly cut out letter "v" and alert str without "v"
var str = "Javascript";
var cut = str.substring(2,3);
var str = "Javascript";
var cut = str.substring(0,2) + str.substring(3);
alert(cut);
You're using the right tool (String#substring). You need two substrings that you put back together, the "Ja" and the "ascript". So:
var str = "Javascript";
var cut = str.substring(0, 2) + str.substring(3);
alert(cut);
Another option would be String#replace, which will replace the first occurrence of what you give it unless you tell it to do it globally with a regex and the g flag (which we won't, because we just want to remove that one v):
var str = "Javascript";
var cut = str.replace("v", "");
alert(cut);
Just for fun, there is another way, but it's a bit silly: You can split the string into an array of single-character strings, remove the third entry from the array, and then join it back together:
var str = "Javascript";
var cut = str.split("").filter(function(_, index) {
return index != 2;
}).join("");
alert(cut);
or
var str = "Javascript";
var cut = str.split("");
cut.splice(2, 1); // Delete 1 entry at index 2
cut = cut.join("");
alert(cut);
...but again, that's a bit silly. :-)
use replace method
var str = "Javascript";
str = str.replace("v", "");
alert(str);

How to count the number of characters without spaces?

I'm new to this, so please understand me;/
I'm creating an app in appery.io and it has to count the number of letters of text inserted by the app user(without spaces).
I have an input field created(input), a button to press and show the result in a label(result)
the code for the button:
var myString = getElementById("input");
var length = myString.length;
Apperyio('result').text(length);
Can you please tell me what is wrong?
To ignore a literal space, you can use regex with a space:
// get the string
let myString = getElementById("input").value;
// use / /g to remove all spaces from the string
let remText = myString.replace(/ /g, "");
// get the length of the string after removal
let length = remText.length;
To ignore all white space(new lines, spaces, tabs) use the \s quantifier:
// get the string
let myString = getElementById("input").value;
// use the \s quantifier to remove all white space
let remText = myString.replace(/\s/g, "")
// get the length of the string after removal
let length = remText.length;
Use this:
var myString = getElementById("input").value;
var withoutSpace = myString.replace(/ /g,"");
var length = withoutSpace.length;
count = 0;
const textLenght = 'ABC ABC';
for (var i = 0, len = textLenght.length; i < len; i++) {
if (textLenght[i] !== ' ')
count++;
}
You can count white spaces and subtract it from lenght of string for example
var my_string = "John Doe's iPhone6";
var spaceCount = (my_string.split(" ").length - 1);
console.log(spaceCount);
console.log('total count:- ', my_string.length - spaceCount)

find first number in a string followed by x amount of characters

string sChar = "_$$$ASDF 123-456-789123123XXX";
string sChar = "$$VIC123-456-789pppEEX";
I would like to parse the above examples of sChar to result in the following value
123-456-789
What this regex would do is find the first Number in the string as well as the next 10 characters. The next 10 characters can be special characters, alpha, or numberic.
Here the solution for you:
var sChar = "_$$$ASDF 123-456-789123123XXX";
//string sChar = "$$VIC123-456-789pppEEX";
var indexDigit = sChar.search(/[\d]/);
var str = sChar.substring(indexDigit, indexDigit+11);
alert(str);
I see an answer like this:
var str = sChar.match(/\d.{10}/);
alert(str)
That won't work:
Try the following:
var sChar = "_$$$ASDF 123-4$6-7";
var sChar2 = "$$VIC987-6$4-3";
var indexDigit = sChar.search(/[\d]/);
var str = sChar.substring(indexDigit, indexDigit+11);
alert(str);//returns "123-4$6-7"
var str2 = sChar2.match(/\d.{10}/);
alert(str2);//returns null

JavaScript get character in sting after [ and before ]

I have some strings like:
str1 = "Point[A,B]"
str2 = "Segment[A,B]"
str3 = "Circle[C,D]"
str4 = "Point[Q,L]"
Now I want to have function that gives me character after "[" and the character before "]". How could I make something like that ?
try this one...
var str = "Point[A,B]";
var start_pos = str.indexOf('[') + 1;
var end_pos = str.indexOf(']',start_pos);
var text_to_get = str.substring(start_pos,end_pos)
alert(text_to_get);
You'd need regex to do that
var matches = /\[(.*?)\]/.exec(str1);
alert(matches[1]);
You can use match() to extract the characters:
str.match(/\[(.*)\]/)[1]
A safer way would be:
var matches = str.match(/\[(.*)\]/);
if(matches) {
var chars = matches[1];
}
Here's an approach which avoids regex.
var str = "Point[A,B]";
var afterOpenBracket = str.split("[")[1]; // returns "A,B]"
var bracketContents = afterOpenBracket.split("]")[0]; // returns "A,B"
There, pretty simple! bracketContents now contains the entirety of the text between the first set of brackets.
We can stop here, but I'll go a step further anyway and split up the parameters.
var parameters = bracketContents.split(","); // returns ["A", "B"]
Or in case u have more [A,C,D,B] and don't want to use regex:
var str1 = "Point[A,C,D,B]";
function extract(str1){
var a = str1.charAt(str1.indexOf('[')+1);
var b = str1.charAt(str1.indexOf(']')-1);
return [a, b];
//or
//a.concat(b); //to get a string with that values
}
console.log(extract(str1));

Categories