How do you remove the first number followed by comma in regex? - javascript

If I have strings ["32145","yes","no","0"] how would like: ,"yes","no","0"? Right now I have the regex below, but that gives me ,yes,no,
.replace(/["'\\[\\]\d]/g,"")
How do I just remove the first number and first comma following that number?

Maybe,
\["\d+",|[\]"]
being replaced with an empty string would work OK.
const regex = /\["\d+",|[\]"]/g;
const str = `["32145","yes","no","0"] `;
const subst = ``;
const result = str.replace(regex, subst);
console.log(result);
Demo
RegEx Circuit
jex.im visualizes regular expressions:

Here is a solution without regex using JSON.parse().
var str = '["32145","yes","no","0"]';
var result = JSON.parse(str); // Convert string to array.
result.shift(); // Remove first array element.
result = result.toString(); // Convert array to string.
console.log(result);

Simply parse the value and remove the first element which is a number
let firstNumRemover = (str) => {
let removeFurther = true
return JSON.parse(str).filter(v => {
if (!isNaN(v) && removeFurther) {
removeFurther = false
return false
}
return true
}).toString()
}
console.log(firstNumRemover(`["32145","yes","no","0"]`))
console.log(firstNumRemover(`["Some random text", "32145","yes","no","0"]`))

Related

How can I remove characters from a string given in an array

for self development purposes I want to create a function with two parameters - string and an array. It should return a string without the letters given in the array.
function filterLetters(str, lettersToRemove) {
}
const str = filterLetters('Achievement unlocked', ['a', 'e']);
Could someone give me any pointers on how to achieve this?
For each letter to be replaced, remove it (i.e. replace it with ''). When done, return the updated string:
function filterLetters(str, lettersToRemove) {
lettersToRemove.forEach(function(letter){
str = str.replaceAll(letter, '');
})
return str
}
Also see How to replace all occurrences of a string in JavaScript.
You can use regex with replaceAll to remove all char from the string.
If you want to consider upper case also then use 'gi' else no need for regex also. str.replaceAll(char, '')
const removeChar = (str, c) => str.replaceAll(new RegExp(`[${c}]`, "gi"), "");
const run = () => {
const str = "Achievement unlocked";
const chars = ["a", "e"];
let result = str;
chars.forEach((char) => {
result = removeChar(result, char);
});
return result;
};
console.log(run());
One easy way to do this would be to just loop over each value in the array and call the replace string method on str with each indices character. The code below does this.
function filterLetters(str, lettersToRemove){
for (const letter of lettersToRemove){
str = str.replaceAll(letter,"");
}
return str;
}
You should just transform the string into array by using split function and loop over that array and check if each character exist in the second argument of your function. To make this function not case sensitive I use toLowerCase to convert character to
function filterLetters(str, lettersToRemove) {
return str.split('').reduce((acc, current)=> {
if(lettersToRemove.indexOf(current.toLowerCase()) == -1){
acc.push(current);
}
return acc;
}, []).join('');
}
const str = filterLetters('Achievement unlocked', ['a', 'e']);
console.log(str);
Create a regular expression by joining the array elements with a | (so a|e), and then use replaceAll to match those letters and replace them with an empty string.
If you want both upper- and lower-case letters removed add the "case-insenstive" flag to the regex. 'gi' rather than 'g'.
function filterLetters(str, lettersToRemove) {
const re = new RegExp(lettersToRemove.join('|'), 'g');
return str.replaceAll(re, '');
}
const str = filterLetters('Achievement unlocked', ['a', 'e']);
console.log(str);

Reversing a string with terminating punctuation results in errors

I am tyring to reverse a string in javascript with the following code.
const reverseString = str => [...str].sort(() => 1).join('');
All my test are passing, except the one in which the string contains punctuations at the end. e.g hungry!, sharpshooter^. What is causing the error?
Test results
Input: "I am hungry!"
Expected: "!yrgnuh ma I"
Received: "u!Iyrgn h ma"
Input: "sharpshooter^"
Expected: "^retoohsprahs"
Received: "h^osaretorhsp"
I guess its because position in ASCII table, why wouldn't you use reverse() ?
const reverseString = str => [...str].reverse().join('')
You can use reverse() to reverse the array before joining the array elements.
function reverseString(str){
return [...str].reverse().join('');
}
console.log(reverseString("I am hungry!"));
console.log(reverseString("sharpshooter^"));
Try this:
const reverseString = str => [...str].sort(() => -1).join('');
or even better...
const reverseString = str => [...str].reverse().join('');
If you don't want to use split reverse and join, use a simple loop
function reverseString(str){
let length = str.length
let final = ''
while(length-- > 0){
final+= str[length]
}
return final
}
console.log(reverseString("I am hungry!"));
console.log(reverseString("sharpshooter^"));

Find characters in a string and add whole word to array when found

var arr = [];
var str='This is mWORDy word docuWORDment';
if (str.indexOf('WORD') > -1) {
arr.push(Whole word here)
}
This works but I need to push the whole words that contains WORD into the array.
So the result should be this:
arr['mWORDy','docuWORDment'];
How can I do this?
You can split the sentence and use filter to filter the array. Use includes to check if a string contains a certain word.
var str = 'This is mWORDy word docuWORDment';
var arr = str.split(" ").filter(o => o.includes("WORD"));
console.log(arr);
Using String.prototype.match() with a simple regular expression:
const str = 'This is mWORDy word docuWORDment';
const result = str.match(/\w*(WORD)\w*/g);
console.log(result);
You can use this regular expression to capture the matches in a group preceded and suffixed by word boundaries and push it into an array.
const pattern = /\b([A-Za-z]+WORD[A-Za-z]+)\b/gm;
const str = `This is mWORDy word docuWORDment`;
let m;
let matchedArr = [];
while ((m = pattern.exec(str)) !== null) {
// Push the first captured group
matchedArr.push(m[1]);
}
console.log(matchedArr);

String cutting with Javascript

I have a string like "home/back/step" new string must be like "home/back".
In other words, I have to remove the last word with '/'. Initial string always has a different length, but the format is the same "word1/word2/word3/word4/word5...."
var x = "home/back/step";
var splitted = x.split("/");
splitted.pop();
var str = splitted.join("/");
console.log(str);
Take the string and split using ("/"), then remove the last element of array and re-join with ("/")
Use substr and remove everything after the last /
let str = "home/back/step";
let result = str.substr(0, str.lastIndexOf("/"));
console.log(result);
You could use arrays to remove the last word
const text = 'home/back/step';
const removeLastWord = s =>{
let a = s.split('/');
a.pop();
return a.join('/');
}
console.log(removeLastWord(text));
Seems I got a solution
var s = "your/string/fft";
var withoutLastChunk = s.slice(0, s.lastIndexOf("/"));
console.log(withoutLastChunk)
You can turn a string in javascript into an array of values using the split() function. (pass it the value you want to split on)
var inputString = 'home/back/step'
var arrayOfValues = inputString.split('/');
Once you have an array, you can remove the final value using pop()
arrayOfValues.pop()
You can convert an array back to a string with the join function (pass it the character to place in between your values)
return arrayOfValues.join('/')
The final function would look like:
function cutString(inputString) {
var arrayOfValues = inputString.split('/')
arrayOfValues.pop()
return arrayOfValues.join('/')
}
console.log(cutString('home/back/step'))
You can split the string on the '/', remove the last element with pop() and then join again the elements with '/'.
Something like:
str.split('/');
str.pop();
str.join('/');
Where str is the variable with your text.

Creating a regex to replace each matched character of a string with same character

In my application, I have an alphanumeric string being passed into my function. This string is typically 17 characters, but not always. I'm trying to write a regex that matches all but the last 4 characters in the string, and replaces them with X (to mask it).
For example
Input: HGHG8686HGHG8686H
Output: XXXXXXXXXXXXX686H
The Regex I wrote to perform the replace on the string is as follows
[a-zA-Z0-9].{12}
Code:
const maskedString = string.replace(/[a-zA-Z0-9].{12}/g, 'X');
The issue I'm having is that it's replacing all but the last 4 characters in the string with just that single X. It doesn't know to do that for every matched character. Any ideas?
you can use a function inside replace to do this, something like this will do:
var str = "HGHG8686HGHG8686H"
var regexp = /[a-zA-Z0-9]+(?=....)/g;
var modifiedStr = str.replace(regexp, function ($2) {
return ('X'.repeat($2.length +1));
});
console.log(modifiedStr);
The simple version: (Easier to read)
const maskedString = string.replace(/(.{4})$|(^(..)|(.))/g, 'X\1'); // or X$1
Now using: [a-zA-Z0-9]
const maskedString = string.replace(/([a-zA-Z0-9]{4})$|(^([a-zA-Z0-9]{2})|([a-zA-Z0-9]{1}))/g, 'X\1'); // or X$1
Note: The reason i match on the START PLUS TWO characters is to offset the first match. (The final 4 characters that are appended at the end.)
Look ahead (?=) to make sure there are at least four following characters.
const regex = /.(?=....)/g;
// ^ MATCH ANYTHING
// ^^^^^^^^ THAT IS FOLLOWED BY FOUR CHARS
function fix(str) { return str.replace(regex, 'X'); }
const test = "HGHG8686HGHG8686H";
// CODE BELOW IS MERELY FOR DEMO PURPOSES
const input = document.getElementById("input");
const output = document.getElementById("output");
function populate() { output.textContent = fix(input.value); }
input.addEventListener("input", populate);
input.value = test;
populate();
<p><label>Input: </label><input id="input"></p>
<p>Output: <span id="output"></span></p>
A non-regexp solution:
const test = "HGHG8686HGHG8686H";
function fix(str) {
return 'X'.repeat(str.length - 4) + str.slice(-4);
}
console.log(fix(test));
You will not find String#repeat in IE.
You can achieve using following method:
var str = "HGHG8686HGHG8686H"
var replaced=''
var match = str.match(/.+/)
for(i=0;i<match[0].length-4;i++){
str = match[0][i]
replaced += "X"
}
replaced += match[0].substr(match[0].length-4)
console.log(replaced);

Categories