Function that modifies string based on unicode number - javascript

I want to write a function that changes each character of the input string based on whether it s a letter or not. If it is a letter, the character should be set to '1' otherwise to '0'. For instance
change('abc123') returns ('111000')
change('12ab3') returns ('00110')
My try:
function change(para){
let newstring=para;
let unicodenum=String.fromCharCode();
for (i=0; i<para.length; i++){
for (j=65; j<91; j++) {
if (unicodenum[j] === para[i])
{
newstring.replace(/para[i]/g, "1")
}
else {
newstring.replace(/para[i]/g, "0")
}
}
}
return newstring
}
Right now, the string is not modified when invoked, but simply returned.

Here is a simple one liner that will do what you needed.
I have used regrex, /[0-9]/g,"0" will replace all numbers with 0 and /[a-z]/g,"1" will replace all letters from a-z with 1.
/g denotes the global flag that will replace all occurrences of 0-9 and a-z. We can also use \d instead of [0-9]
/[0-9]/g,"0" is used before /[a-z]/g,"1" because you also want numbers to be converted to "0". If we first convert letters to numbers then everything in the string will become number and all you will get is 0. So it has to be in this specific order only.
let change=(string)=>string.replace(/[0-9]/g,"0").replace(/[a-z]/g,"1")
console.log(change('abc123'))
console.log(change('12ab3'))

Related

Find how many times a char is repeated in a string and remove those repeated chars by a dynamic number

I would like to write a function that recieves two parameters: String and Number.
The function will return another string that is similar to the input string, but with certain characters
removed.
The function will remove characters from consecutive runs of the same
character, where the length of the run is greater than the input parameter.
for example:
"aaab", 2 => "aab"
"aabb", 1 => "ab"
"aabbaa", 1 => "aba"
What I did:
function doSomething(string,number) {
let repeatCount = 0
debugger;
for (let i = 0; i < string.length; i++) {
if(string[i] == string[i+1]){
repeatCount++
}
if(repeatCount > number ){
string.replace(string[i],'')
}
}
console.log(string)
}
doSomething('aaab',2)
The console.log(string) prints 'aaab' but I want it to print 'aab' because the number is 2 and the char 'a' is repeated 3 times.
If there is another better way to do it , I will be happy to learn.
If there is another better way to do it, I will be happy to learn.
You could go with a .replace() approach and a regular expression with a backreference to match consecutive letters. Then you can use .slice() to remove the additional letters to get it to the defined length like so:
function shorten(string,number) {
return string.replace(/(.)\1+/g, m => m.slice(0, number))
}
console.log(shorten("aaab", 2))// => "aab"
console.log(shorten("aabb", 1))// => "ab"
console.log(shorten("aabbaa", 1))// => "aba"
The above regular expression will match any character and group it (.). This matched character is then checked for again to see if it is repeated one or more times by using \1+. The replacement function will then be invoked for each consecutive runs of letters, which you can trim down to your desired length by using .slice().
For example, take the string aabbaa. The regular expression tries to find consecutive runs of characters. The (.) would match any character, in this case, it finds "a" and puts it into a "capture group" called "1". Now the regular expression tries to find whether “a” is followed by one or more “a” characters by checking if the grouped (ie the character “a”) follows it one or more times. This is done using \1+. The first section of the aabbaa string that this regular expression matches is "aa", as we match the “a”, capture it, and find that it is repeated with \1+. When a match is found, the function m => m.slice(0, number) is ran. This function takes the match (m), which in this case is "aa", and returns the sliced version of it, giving "a". This then replaces the "aa" we matched from the original string with the value returned, thus causing "aa" to be converted to "a" (note this conversion doesn't modify the original string, it occurs in the new string that gets returned by the replace method). The /g at the end of the regular expression means repeat this for the entire string. As a result, our regular expression moves on and finds "bb". The function then gets called again but this time with m set as "bb", causing "bb" to be converted to "b". Lastly, we match "aa", this causes "aa" to get converted to "a". Once replace has finished going through the entire string, it returns the result with the returned values (as well as the part of the original string it didn’t modify) and so it gives "aba"
Not that the rest of your code is correct. But one fundamental mistake you have made is that, strings in javascript is immutable. You cannot change an element of the string like that.
string.replace(string[i],'')
This won't change 'string'. You have to make another string from it.
let str = string.replace(string[i],'')
function doSomething(string,number) {
let repeatCount = 0
debugger
let sameletter=string[0]
for (let i = 0; i < string.length;i++) {
if(string[i] == sameletter){
repeatCount++
if(repeatCount>number){
var result = string.split('')
result.splice(i, 1)
string = result.join('')
i--
}
}
else{
sameletter=string[i];
repeatCount=1;
}
}
console.log(string)
}
doSomething('aaaabbbbeeeffffgggggggggg',2)
Try this

JS - Iterate through text snippet character by character, skipping certain characters

I am using JS to loop through a given text, refered to in below pseudo as "input_a".
Based on the contents of another, and seperate text "input_b" I would like to manipulate the individual characters of text "input_a" by assigning them with a boolean value.
So far I've approached it the following way:
for (i=0; i < input_a.length; i++) {
if (input_b[i] == 0){
//do something to output
}
}
Now the issue with this is that the above loop, being that it uses .length also includes all blank/special characters whereas I would only like to include A-Z - ommitting all special characters (which in this case would not be applicable to recieve the boolean assigned to them).
How could I approach this efficiently and elegantly - and hopefully without reinventing the wheel or creating my own alphabet array?
Edit 1: Forgot to mention that the position of the special characters needs to be retained when the manipulated input_a is finally delivered as output. This makes an initial removal of all special characters from input_a a non viable option.
It sounds like you want input_a to retain only alphabetical characters - you can transform it easily with a regular expression. Match all non-alphabetical characters, and replace them with the empty string:
const input_a = 'foo_%%bar*&#baz';
const sanitizedInputA = input_a.replace(/[^a-z]+/gi, '');
console.log(sanitizedInputA);
// iterate through sanitizedInputA
If you want the do the same to happen with input_b before processing it, just use the same .replace that was used on a.
If you need the respective indicies to stay the same, then you can do a similar regular expression test while iterating - if the character being iterated over isn't alphabetical, just continue:
const input_a = 'foo_%%bar*&#baz';
for (let i = 0; i < input_a.length; i++) {
if (!/[a-z]/i.test(input_a[i])) continue;
console.log(input_a[i]);
}
You can check if the character at the current position is a letter, something like:
for (i=0; i < input_a.length; i++) {
if(/[a-z]/i.test(input_a[i])){
if (input_b[i] == 0){
//do something to output
}
}
}
the /[a-z]/i regex matches both upper and lower case letters.
Edited as per Edit 1 of PO
If you would like to do this without RegEx you can use this function:
function isSpecial(char) {
if(char.toLowerCase() != char.toUpperCase() || char.toLowerCase.trim() === ''){
return true;
}
return false;
}
You can then call this function for each character as it comes into the loop.

javascript search string for sequential periods [duplicate]

This question already has answers here:
Regex to check consecutive occurrence of period symbol in username
(2 answers)
Closed 4 years ago.
How do I search a string for multiple periods in a row, for example "...".
string.search(/.../);
string.search("[...]");
The above will return true even if a single period is detected.
string.search("...");
This is even worse as it always returns true, even if there is no period.
var banlist = ["item1", "item2", "[...]"];
I am searching each string in the list, and I need to be able to search for "...".
Edit:
Now I have a new problem. three periods exactly "..." comes out to unicode character 8230, and it is not found in the search. Any other sequence of periods can be found except for three "...".
You need to escape the . character using a backslash \
let str = "som.e ra...ndom s.tring..";
console.log(str.match(/\.{2,}/g));
where {2,} indicates that there has to be at least 2 . characters in a row and /g indicates that the whole string should be evaluated. Notice that the . is escaped.
Use \\ to escape the dot in your search.
For example '\\.\\.' or '\\.{2}'
string.search() is useful for getting the index of the first occurrence of a pattern. It returns -1 if pattern isn't found.
string.search('\\.{2}')
With string.search going through the list would be something like
for (let i = 0; i < banlist.length; i++) {
if (banlist[i].search('\\.{2}') != -1) {
// Do something
}
}
If you don't need the index and just want to know if there are 2 or more dots in the string, string.match might be useful since it returns null when the pattern doesn't match.
string.match('\\.{2}')
With string.match going through the list would be something like
for (let i = 0; i < banlist.length; i++) {
if (banlist[i].match('\\.{2}')) {
// Do something
}
}

Regular expression to match 0 or 1

I need a regexp to match either 0 or 1 entered into a field and no other characters at all, neither numeric nor alphas. How can I do it?
Single character, 0 or 1:
/^[01]$/
Multiple 0s or 1s (any order, no other characters):
/^[01]+$/g
Demo (Just add a + for the second example. The gm at the end in the demo is just for the example because there are multiple lines for test cases)
A simple 0|1 expression should work.
([01])
http://rubular.com/r/TMu6vsx6Dn
If you only want the first occurrence, this will work as well.
(^[01])
http://rubular.com/r/i3brvRutCg
Try this regex: /^(0|1)$/
Example:
/^(0|1)$/.test(0); // true
/^(0|1)$/.test(1); // true
/^(0|1)$/.test(2); // false
/^(0|1)$/.test(1001) // false
I would suggest simple string evaluation here since you have only two known acceptable values in the input string:
var input; // Your input string assume it is populated elsewhere
if (input === '0' || input === '1') {
// Pass
}
Note the use of strict string comparison here to eliminate matches with truthy/falsey values.
If you are really hell-bent on a regex, try:
/^[01]$/
The key here is the beginning ^ and ending $ anchors.

Javascript regular expression match on string followed by number?

I have a string of the format: string:num where num is any number but string is a known string that I need to match on. I'd like to have this in an if statement as:
if( it matches 'string:' followed by a number) {
//do something
}
You want ...
if (stringYouHave.match(/^string:([0-9]+)$/)) {
// do something
}
This includes:
^ beginning of the string
string: the literal "string:" you mentioned
(.....) This subexpression, which you can refer to later if you need to know which number is in the string (though in this particular case, you could also just replace 'string:' with '')
[0-9] a character between 0 and 9 (i.e., a digit)
+ Must have at least one "of those" (i.e., digits mentioned above), but can have any number
$ end of the string
if( it.match(/^string:\d+$/) ( {
...
}
If you want only to check if the input string matches the pattern, you can use the RegExp.test function:
if (/^string:[0-9]+$/.test(input)){
//..
}
or with the String.search function:
if (input.search(/^string:[0-9]+$/) != -1){
//..
}
If you want to validate and get the number:
var match = input.match(/^string:([0-9]+)$/),
number;
if (match){
number = +match[1]; // unary plus to convert to number
// work with it
}
The above is good for integer numbers; if you want floating point numbers, or even scientific notation (as understood in C-like languages), you'll want something like this:
if (stringYouHave.match(/^string:[+-]?[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?$/))
{
// do something
}
You can remove the first [+-]? if you don't care about sign, the (.[0-9]+)? if you don't care about floating points, and the ([eE][+-]?[0-9]+)? if you don't care about scientific notation exponents. But if there's a chance you DO want to match those, you want to include them as optional in the regex.
if(teststring.match(new RegExp("^" + knownstring + ":\d+$"))) {
// some code
}
if(!!"string:5456".match(/^string:\d+$/)) { ... }
Number is a integer in the example above.

Categories

Resources