I have an array like ['adsd','ssd2','3244']. I want to replace a string if it contains any alphabet with '----'. So, the above array should be like ['----','----','3244']. How can I do that? Can I so it with regular expression?
2 Answers
yourArray.map(str => /[a-z]/i.test(str) ? '----' : str)
4 Comments
David Thomas
What exactly is the OP supposed to learn from this unexplained code? How are they supposed to learn from this unexplained code?
kshetline
@DavidThomas, it's simple enough that just looking at it and wondering how it works someone can learn from it by example. It hardly needs to be explained step-by-step to be a learning experience.
Benjamin
This won't work in any version of IE, including the latest one, because IE doesn't support arrow functions.
David Thomas
Read the question, does it seem the OP is likely to understand your answer? It is, however, a subjective opinion. And without an explanatory edit and update I stand by mine.
['adsd','ssd2','3244'].map(function(item) {
return /[a-z]/i.test(item) ? '----' : item;
});
Edit: a bit of explanation about what's happening here.
map() applies a function that transforms every element of the array. More info.
/[a-z]/i is a regex that matches every character in the alphabet. The i makes it case-insensitive, so it matches a and also A.
test checks whether a given string matches the regex. More info.
? '----' : item uses a ternary operator to return either ---- or the original string, depending on whether the string has any alphabetic character. More info.
1 Comment
David Thomas
What exactly is the OP supposed to learn from this unexplained code? How are they supposed to learn from this unexplained code?
-strings be the same length of the array elements you're replacing?