how to extract numbers from string using Javascript? - javascript

how to extract numbers from string using Javascript?
Test cases below:
string s = 1AA11111
string s1= 2111CA2
string s result = 111111
string s1 result = 211112
My code below is not working:
var j = 0;
var startPlateNums = "";
while (j <= iStartLength && !isNaN(iStartNumber.substring(j, j + 1))){
startPlateNums = startPlateNums + iStartNumber.substring(j, j + 1);
j++;
}

How about a simple regexp
s.replace(/[^\d]/g, '')
or as stated in the comments
s.replace(/\D/g, '')
http://jsfiddle.net/2mguE/

You could do:
EDITED:
var num = "123asas2342a".match(/[\d]+/g)
console.log(num);
// THIS SHOULD PRINT ["123","2342"]

A regex replace would probably the easiest and best way to do it:
'2111CA2'.replace(/\D/g, '');
However here's another alternative without using regular expressions:
var s = [].filter.call('2111CA2', function (char) {
return !isNaN(+char);
}).join('');
Or with a simple for loop:
var input = '2111CA2',
i = 0,
len = input.length,
nums = [],
num;
for (; i < len; i++) {
num = +input[i];
!isNaN(num) && nums.push(num);
}
console.log(nums.join(''));

Related

“str.fromCharCode is not a function”

Im getting the following errors:
str.fromCharCode is not a function
newStr.push is not a function
I have no clue why I’m getting those errors tbh. I might be using methods the wrong way
function rot13(str) {
var newStr = str;
for (i = 0; i < str.length; i++) {
str.fromCharCode(str[i] - 13);
newStr.push(i);
}
return newStr;
}
// Change the inputs below to test
console.log(
rot13("SERR PBQR PNZC")
)
You could try something like:
function rot13(str) {
var newStr = [];
for(i = 0; i < str.length; i++){
let x = String.fromCharCode(str[i].charCodeAt()-13);
newStr.push(x);
}
return newStr.join("");
}
It is String.fromCharCode, not myString.fromCharCode
Lastly you want charCodeAt to subtract from
Also you cannot push a char to a string. push is an Array method
function rot13(str) {
var newStr = []; // using an array - you can use += to concatenate to string
for (i = 0; i < str.length; i++) {
// I suggest you do not convert the space.
// Here I converted it to another type of space but you can use " " if you want
var x = str[i] == " " ? "\u2005":String.fromCharCode(str[i].charCodeAt(0) - 13);
newStr.push(x);
}
return newStr.join("");
}
// Change the inputs below to test
console.log(
rot13("SERR PBQR PNZC")
)

How to repeat characters in a string in javascript by using slice function?

Can anyone shed light on how to frame a javascript function with two parameters: string and character, and only by using the slice method, return the number of times "a" appears in "lava"?
without slice method
var fruits= "lavaaagg";
var count=0;
for(var i=0;i<fruits.length;i++){
if(fruits[i]!='a')
count++;
}
console.log(fruits.length-count);
I'm not sure why you need the slice method. The slice method isn't for searching substrings (or characters in your case), it extracts a substring.
This should work fine:
function howManyCharInStr(str, char) {
return str.split(char).length - 1;
}
Step-by-step explanation:
str.split(char)
Creates an array of str substrings, using char as a separator. For example:
'fooXbazXbar'.split('X')
// Evaluates to ['foo', 'baz', 'bar']
'lorem ipsum dolor'.split('m')
// Evaluates to ['lore', ' ipsu', ' dolor']
Notice how the array returned has a length of n+1 where n is the number of separators there were. So use
str.split(char).length - 1;
to get the desired result.
For getting number of charecters count
<script type="text/javascript">
function FindResults() {
var firstvariable= document.getElementById('v1');
var secondvariable = document.getElementById('v2');
var rslt = GetCharecterCount(firstvariable, secondvariable );
}
function GetCharecterCount(var yourstring,var charecter){
var matchesCount = yourstring.split(charecter).length - 1;
}
</script>
using slice method
var arr = yourstring.split(charecter);
for( var i = 0, len = arr.length; i < len; i++ ) {
var idx = yourstring.indexOf( arr[i] );
arr[i] = pos = (pos + idx);
str = str.slice(idx);
}
var x= arr.length-1;
example http://jsfiddle.net/rWJ5x/2/
Using slice method
function logic(str,char){
var count = 0;
for(var i = 0; i < str.length; i++){
if(str.slice(i,i+1) == char){
count++;
}
}
return count;
};
console.log( "count : " + logic("lava","a") );
repeat last character of sting n number of times..
function modifyLast(str, n) {
var newstr = str.slice(-1)
var newlaststr = newstr.repeat(n-1)
var concatstring = str.concat(newlaststr);
return concatstring;
}
//modifyLast();
console.log(modifyLast("Hellodsdsds", 3))

Take random letters out from a string

I want to remove 3 RANDOM letters from a string.
I can use something like substr() or slice() function but it won't let me take the random letters out.
Here is the demo of what I have right now.
http://jsfiddle.net/euuhyfr4/
Any help would be appreciated!
var str = "hello world";
for(var i = 0; i < 3; i++) {
str = removeRandomLetter(str);
}
alert(str);
function removeRandomLetter(str) {
var pos = Math.floor(Math.random()*str.length);
return str.substring(0, pos)+str.substring(pos+1);
}
If you want to replace 3 random charc with other random chars, you can use 3 times this function:
function substitute(str) {
var pos = Math.floor(Math.random()*str.length);
return str.substring(0, pos) + getRandomLetter() + str.substring(pos+1);
}
function getRandomLetter() {
var letters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var pos = Math.floor(Math.random()*letters.length);
return letters.charAt(pos);
}
You can split the string to an array, splice random items, and join back to a string:
var arr = str.split('');
for(var i=0; i<3; ++i)
arr.splice(Math.floor(Math.random() * arr.length), 1);
str = arr.join('');
var str = "cat123",
amountLetters = 3,
randomString = "";
for(var i=0; i < amountLetters; i++) {
randomString += str.substr(Math.floor(Math.random()*str.length), 1);
}
alert(randomString);
fiddle:
http://jsfiddle.net/euuhyfr4/7/
This answer states that
It is faster to slice the string twice [...] than using a split followed by a join [...]
Therefore, while Oriol's answer works perfectly fine, I believe a faster implementation would be:
function removeRandom(str, amount)
{
for(var i = 0; i < amount; i++)
{
var max = str.length - 1;
var pos = Math.round(Math.random() * max);
str = str.slice(0, pos) + str.slice(pos + 1);
}
return str;
}
See also this fiddle.
you can shuffle characters in your string then remove first 3 characters
var str = 'congratulations';
String.prototype.removeItems = function (num) {
var a = this.split(""),
n = a.length;
for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("").substring(num);
}
alert(str.removeItems(3));
You can use split method without any args.
This would return all chars as a array.
Then you can use any randomiser function as described in Generating random whole numbers in JavaScript in a specific range? , then use that position to get the character at that position.
Have a look # my implementation here
var str = "cat123";
var strArray = str.split("");
function getRandomizer(bottom, top) {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
alert("Total length " + strArray.length);
var nrand = getRandomizer(1, strArray.length);
alert("Randon number between range 1 - length of string " + nrand);
alert("Character # random position " + strArray[nrand]);
Code # here https://jsfiddle.net/1ryjedq6/

Make a character capitalize within a strin in javascript not working

I am trying to capitalize a character within a string in javascript, my codes are :
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = "string";
for(m = 0; m < str.length; m++){
if(str[m] == "r"){
str[m+1] = str[m+1].toUpperCase();
}
}
alert(str);
}
</script>
So what I am trying to do is, if the character is r,capitalize the next character. But is not woking means its the same string alerting.
Strings in JavaScript are immutable, you need to create a new string and concatenate:
function myFunction() {
var str = "string";
var res = str[0];
for(var m = 1; m < str.length; m++){
if(str[m-1] == "r"){
res += str[m].toUpperCase();
} else {
res += str[m];
}
}
}
But you could simply use regex:
'string'.replace(/r(.)/g, function(x,y){return "r"+y.toUpperCase()});
String are immutable. So You can convert string to array and do the replacements and then convert array to string. Array are mutable in Javascript.
var str = "string".split('');
for(m = 0; m < str.length - 1; m++){
if(str[m] == "r"){
str[m+1] = str[m+1].toUpperCase();
}
}
alert(str.join(''));
Try this
<script>
function myFunction() {
var p='';
var old="r";
var newstr =old.toUpperCase();
var str="string";
while( str.indexOf(old) > -1)
{
str = str.replace(old, newstr);
}
alert(str);
}
</script>
But you it will not work in alart.
Hope it helps
var str = "string";
for(m = 0; m < str.length; m++){ // loop through all the character store in varable str.
if(str[m] == "r") // check if the loop reaches the character r.
{
alert(str[m+1].toUpperCase()); // take the next character after r make it uppercase.
}
}

JavaScript Count String Without Spaces

GEN000 AMA000 GaT000
I only need to count the number of text without the spaces
Just as an alternative approach:
'GEN000 AMA000 GaT000'.match(/\S/g).length; // 18
However, the fastest solution should always be a single for loop:
var str = 'GEN000 AMA000 GaT000',
count = 0;
for (var i = 0, len = str.length; i < len; i++) {
if (str[i] !== ' ')
count++;
}
var text = "GEN000 AMA000 GaT000";
var length = text.split(" ").join("").length;
console.log(length);
Try this simple solution,
alert(str.replace(/\s/g, "").length);
Example

Categories

Resources