Extract numbers from string and wrap them in HTML - javascript

My requirement is as follows. I have this example text:
html
9216143567 is the number and other one is 0112388908
Now I want a JS function which finds then numbers which are together and greater than 8 in number and adds html code around them like below
9216143567 is the number and other one is 0112388908
What is the right way to do this?

Try this. Takes string as input and gives HTML as output.
var abc = 'ei32eoeiq 9216143567 is the number and other one is 0112388908, 7878787878,deewodiwqodiwp 9898903232';
var splitArray = abc.match(/\d+/g);
for(var i = 0 ; i < splitArray.length; i++){
value = splitArray[i];
if(value.length>8) {
abc = abc.replace(value, ''+value+'');
}
}
console.log(abc);
document.getElementById("ans").innerHTML = abc;
<div id="ans"></div>

This can be solved with a regex: (\d{8,})[^\d]+(\d{8,})/g
It matches two matching groups, each of them wraps a number of at least 8 digits; where the two numbers are separated by at least one non-digit character.
let input = document.getElementById("input").innerHTML;
let regex = /(\d{8,})[^\d]+(\d{8,})/g;
let matches = regex.exec(input);
document.getElementById("ans").innerHTML = "OUTPUT: The first num is " + matches[1] + " and the second is " + matches[2];
<div id="input">
INPUT: 9216143567 is the number and other one is 0112388908
</div><br>
<div id="ans"></div>
Edit:
If you want to extract a dynamic number of numbers, you can use a simpler regex, \d{8,}. I've also modified the code so it replaces the original number with a URL that directs to it.
let input = document.getElementById("input").innerHTML;
let regex = /\d{8,}/g;
let match;
let matches_array = [];
while (match = regex.exec(input)) {
matches_array.push(match);
}
for (let i = 0; i < matches_array.length; i++) {
let tmp = '' + matches_array[i] + '';
input = input.replace(new RegExp(matches_array[i], "g"), tmp);
}
document.getElementById("ans").innerHTML = input;
<div id="input">
9216143567 is the number and other one is 0112388908 and the third is 1234567890
</div><br>
<div id="ans"></div>

Related

How to remove delimiters from a given RegEx?

my input:
str = "User-123"
o/p:
name: User
id: 123
another input:
str = "User 123"// current this works with my regex.
o/p: As above
other possible inputs:
str = "User:123"
str = "User/123"
str = "User:123"
code:
let m = value.match(/([a-z]+\s*\d+)\s+([a-z]+\s*\d+|\d+\s*[a-z]+)/i);
if (m) {return true}
else {return false}
if I have delimiters the above code return false as it does not find the match for the delimiters. I want to return true for all the scenarios listed above.
currently it removes only the whitespaces, how can I remove delimiters from this regex as well?
It looks like you just want to split on a non-alphanumeric character:
let inputs = [
"User:123",
"User/123",
"User:123",
"User-123",
"User 123"
]
for (i of inputs){
let [name, id] = i.split(/[^a-z0-9]/i)
console.log("name:", name, "id:", id)
}
You might consider simplifying your expression. Using capturing groups, you can simply add/remove any delimiters that you wish. For instance, this expression shows how you might use capturing group:
([A-z]+)(:|\/)([0-9]+)
Graph
This graph shows how the expression work:
Code
This code shows how to do so and does a basic benchmark with 1 million times repeat.
repeat = 1000000;
start = Date.now();
for (var i = repeat; i >= 0; i--) {
var string = 'User/123';
var regex = /([A-z]+)(:|\/)([0-9]+)/g;
var match = string.replace(regex, "$1$3");
}
end = Date.now() - start;
console.log(match + " is a match 💚 ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");

Finding the index to a non-specified character

Let's say for example I have a string
thisIsThisTuesday Day
I want to find the index of all the capital letters, test if there is a space before it, and if not insert one. I would need the index of each one.
At least from what I can see indexOf(String) will only produce the index of the first occurance of the character T/t
This :
for(i=0;i<str.length;i++){
let char=str[i];
if(isNaN(char*1)&&char==char.toUpperCase()){
y=str.indexOf(char);
console.log(char,y)
}
}
would produce the capital letters, and their indexes but will only display the first occurrence of the character in question. I feel pretty confident that the part I am missing is a for() loop in order to move the index iteration..but it escapes me.
Thank you in advance!
You can use a regex:
It matches any non-whitespace character followed by a capital letter and replaces it by the two characters with a space between.
const str = "thisIsThisTuesday Day";
const newstr = str.replace(/([^ ])([A-Z])/g, "$1 $2");
console.log(newstr);
You can use the following regular expression:
/(?<=\S)(?=[A-Z])/g
The replace will insert spaced between characters which are non-space followed by a capital letter.
See example below:
let str = "thisIsThisTuesday Day";
const res = str.replace(/(?<=\S)(?=[A-Z])/g, ' ');
console.log(res);
Note: As pointed out ?<= (positive lookbehind) is currently not be available in all browsers.
Actually, the String.indexOf function can take a second argument, specifying the character it should start searching from. Take a look at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
But, if you just want to find all capital letters and prefix them with a space character, if one is not found, there are many approaches, for example:
var str = "thisIsThisTuesday Day";
var ret = '';
for (var i=0; i<str.length; i++) {
if (str.substr(i, 1) == str.substr(i, 1).toUpperCase()) {
if ((i > 0) && (str.substr(i - 1,1) != " "))
ret += " ";
}
ret += str.substr(i,1);
}
After running this, ret will hold the value "this Is This Tuesday Day"
You could iterate over the string and check if each character is a capital. Something like this:
const s = 'thisIsThisTuesday Day';
const format = (s) => {
let string = '';
for (let c of s) {
if (c.match(/[A-Z]/)) string += ' ';
string += c;
}
return string;
};
console.log(format(s));
Or alternatively with reduce function:
const s = 'thisIsThisTuesday Day';
const format = (s) => s.split('').reduce((acc, c) => c.match(/[A-Z]/) ? acc + ` ${c}` : acc + c, '');
console.log(format(s));

How to not Count Spaces in Search Box? [duplicate]

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)

Separate characters and numbers from a string

I have a string variable that contain character and numbers like this
var sampleString = "aaa1211"
Note that variable always start with a character/s and end with number/s. Character and number size is not fixed. It could be something like followings
var sampleString = "aaaaa12111"
var sampleString = "aaa12111"
I need to separate the characters and numbers and assign them into separate variables.
How could I do that ?
I try to use split and substring but for this scenario I couldn't apply those. I know this is a basic question but i'm search over the internet and I was unable to find an answer.
Thank you
Please use
[A-Za-z] - all letters (uppercase and lowercase)
[0-9] - all numbers
function myFunction() {
var str = "aaaaAZE12121212";
var patt1 = /[0-9]/g;
var patt2 = /[a-zA-Z]/g;
var letters = str.match(patt2);
var digits = str.match(patt1);
document.getElementById("alphabets").innerHTML = letters;
document.getElementById("numbers").innerHTML = digits;
}
Codepen-http://codepen.io/nagasai/pen/pbbGOB
A shorter solution if the string always starts with letters and ends with numbers as you say:
var str = 'aaaaa12111';
var chars = str.slice(0, str.search(/\d/));
var numbs = str.replace(chars, '');
console.log(chars, numbs);
You can use it in a single regex,
var st = 'red123';
var regex = new RegExp('([0-9]+)|([a-zA-Z]+)','g');
var splittedArray = st.match(regex);
var num= splittedArray[0];
var text = splittedArray[1];
this will give you both the text and number.
Using Match
const str = "ASDF1234";
const [word, digits] = str.match(/\D+|\d+/g);
console.log(word); // "ASDF"
console.log(digits); // "1234"
The above will work even if your string starts with digits.
Using Split
with Positive lookbehind (?<=) and Positive lookahead (?=):
const str = "ASDF1234";
const [word, digits] = str.split(/(?<=\D)(?=\d)/);
console.log(word); // "ASDF"
console.log(digits); // "1234"
where \D stands for not a digit and \d for digit.
Use isNaN() to differentiate
var sampleString = "aaa1211"
var newnum =""
var newstr =""
for(var i=0;i<sampleString.length;i++){
if(isNaN(sampleString[i])){
newstr = newstr+sampleString[i]
}else{
newnum= newstr+sampleString[i]
}
}
console.log(newnum) //1121
console.log(newstr) //aaa
If you're like me, you were looking to separate alphabets and numbers, no matter what their position is, Try this:
var separateTextAndNum = (x) => {
var textArray = x.split('')
var text = []
var num = []
textArray.forEach(t=>{
if (t>-1) {
num.push(t)
} else {
text.push(t)
}
})
return [text, num]
}
For ex - if you try this:
separateTextAndNum('abcd1234ava') // result [["a","b","c","d","a","v","a"],["1","2","3","4"]]
This isn't beautiful but it works.
function splitLettersAndNumbers(string) {
var numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
var numbers, letters, splitIndex;
for (var i = 0; i < string.length; i++) {
if (numbers.indexOf(string[i]) > -1) {
letters = string.substring(0, i);
numbers = string.substring(i);
return [letters, numbers];
}
}
// in the chance that you don't find any numbers just return the initial string or array of the string of letters
return [string];
}
Essentially just looping through the string until you find a number and you split it at that index. Returning a tuple with your letters and numbers. So when you run it you can do something like this:
var results = splitLettersAndNumbers(string);
var letters = results[0];
var numbers = results[1];
A functional approach...
var sampleString = "aaaaa12111";
var seperate = sampleString.split('').reduce(function(start , item){
Number(item) ? start[0] += item : start[1] += item;
return start
},['',''])
console.log(seperate) //["12111", "aaaaa"]
You can loop through the string length, check it & add to the variable.
It is not clear if you want to assign each of the character to a variable or all alphabets to one variable & integers to another.
var sampleString = "aaa12111"
var _num = "";
var _alp = "";
for (var i = 0; i < sampleString.length; i++) {
if (isNaN(sampleString[i])) {
_num += sampleString[i];
} else {
_alp += sampleString[i];
}
}
console.log(_num, _alp)

alerts that concatenate rather than add

super remedial question that I just cant quite figure out (new to javascript).
I need to find a way to prompt for a string of text and then alert that string of text 3 times. I have tried the + sign in my alert but that would give me NaN or just an addition rather than just the string. For example if I input 2 it would return 6 rather than 222 which I need.
One way is to include strings in your concatenation:
alert(num+''+num+''+num);
Another is to convert the number to a string first:
var str = num.toString();
alert(str+str+str);
The whole thing would be:
var num = +prompt("Enter a number");
var str = num.toString();
alert(str + str + str);
Just include a string somewhere in between:
2+''+2+2
E.g.
var input = prompt('type something'), result = '';
for(var i = 0; i < 3; i++)
result += input;
console.log(result);
http://jsfiddle.net/35tp3/
Try this:
var number = 2, repeat = 3;
Array(repeat+1).join( number );
That will output "222"
If you want to add a space:
Array(repeat+1).join(" " + number).trim();
Which will output "2 2 2"

Categories

Resources