This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 2 years ago.
the replace function isnt working as a thought it would. came across this piece of code. i know the replace function is to replace all punctuation marks so as to not count them as letters. but when i log a string including punctuations it counts them as well. trying to figure out why
const getLetterCount = (stringToTest) => {
const wordArray = stringToTest.split('');
let totalLetters = 0;
for (let word of wordArray) {
word.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
totalLetters += word.length;
}
console.log(totalLetters);
}
getLetterCount('boy/girl?') // returns 9 ( counting punctuation as well)
String.prototype.replace()
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.
You have to reassign the new value to the variable (word).
const getLetterCount = (stringToTest) => {
const wordArray = stringToTest.split('');
let totalLetters = 0;
for (let word of wordArray) {
word = word.replace(/[.,\/#!$%\^&\*;:{}=\-_` ~()]/g, "");
totalLetters += word.length;
}
console.log(totalLetters);
}
getLetterCount('boy/girl?') // returns 9 ( counting punctuation as well)
Related
This question already has answers here:
Difference between codePointAt and charCodeAt
(3 answers)
Closed 2 years ago.
Getting the first character in a string is fairly straightforward.
const str = 'abc'
str[0] // 'a'
However, when javascript sees a unicode string, it will return the first byte of a multi-byte unicode character.
const strUnicode = '💖hi'
strUnicode[0] // '�'
Is it possible to return the first complete unicode character?
const strUnicode = '💖hi'
f(strUnicode) // '💖'
Issue is that symbols are 16-bit characters. So it takes 2 positions in a character array.
Idea:
Loop over string and validate if current character is a symbol or not.
If symbol, take character at i and i+1. Increment i to skip the processed character
If not, just pick one character
function getCharacters(str) {
const parts = []
for(let i = 0; i< str.length; i++) {
if (str.charCodeAt( i ) > 255) {
parts.push(str.substr(i, 2))
i++
} else {
parts.push(str[i])
}
}
return parts
}
const strUnicode = '💖hi'
console.log( getCharacters(strUnicode) )
This question already has answers here:
Alternation operator inside square brackets does not work
(2 answers)
What's the difference between () and [] in regular expression patterns?
(6 answers)
Closed 3 years ago.
Attempting to create a regex expression that splits a string at ',' and '\n' and then a passed in custom delimiter (which is signified by firstChar in my code).
Format for the string being passed in: {delimiter}\n{numbers}. I've used regex101 online and it seems to work on there but in my actual code it doesn't split at the custom delimiter so not sure what I'm doing wrong.
if (str.includes('\n')) {
let firstChar = str.slice(0, 1);
if (parseInt(firstChar)) {
strArr = str.split(/,|\n/) ;
} else {
strArr = str.split(/[,|\n|firstChar]/);
}
}
expect ';\n2;5' to equal 7 but my array splits into [";", "2;5"] for some reason.
Your first character isn't a number so you go to else condition directly, if you want a dynamic regex then you need to build it using RegExp
Also you don't need character class here
/[,|\n|firstChar]/
it should be
/,|\n|firstChar/
let splitter = (str) => {
if (str.includes('\n')) {
let firstChar = str.slice(0, 1);
if (parseInt(firstChar)) {
return str.split(/,|\n/);
} else {
let regex = new RegExp(`,|\\n|\\${firstChar}`, 'g') // building a dynamic regex here
return str.split(regex).filter(Boolean)
}
}
}
console.log(splitter(";\n2;5"))
console.log(splitter("*\n2*5"))
This question already has answers here:
Remove trailing numbers from string js regexp
(2 answers)
Closed 3 years ago.
How would I remove _100 from the end of the string, It should be removed only at the end of the string.
For e.g
marks_old_100 should be "marks_old".
marks_100 should be "marks".
function numInString(strs) {
let newStr = ''
for (let i = 0; i < strs.length; i++) {
let noNumRegex = /\d/
let isAlphRegex = /[a-zA-Z]$/
if (isAlphRegex.test(strs[i])) {
newStr += strs[i]
}
}
return newStr
}
console.log(numInString('marks_100'))
Please check the following snippet:
const s = 'marks_old_100';
// remove any number
console.log(s.replace(/_[0-9]+$/, ''));
// remove three digit number
console.log(s.replace(/_[0-9]{3}$/, ''));
// remove _100, _150, _num
console.log(s.replace(/_(100|150|num)$/, ''));
Try:
string.replace(/_\d+$/g, "")
It makes use of regexes, and the $ matches the end of the string. .replace then replaces it with an empty string, returning the string without \d+ on the end. \d matches any digits, and + means to match more one or more.
Alternatively, if you want to match the end of a word, try:
string.replace(/_\d+\b/g, "")
which utilises \b, to match the end of a word.
This question already has answers here:
JavaScript Number Split into individual digits
(30 answers)
Closed 5 years ago.
"2+3-8*5"
2
3
8
5
how to split this string and save different variable
Here you can split your string into an array for multiple delimiters.
var strVal = "2+3-8*5";
var resp = strVal.split(/(?:\+|\-|\*)/);
console.log("Resp: " , resp);
#Gufran solution is great with regex. If you don't want to use regex you can use isNaN with loop.
var str = "2+3-8*5";
var result = [];
for (var i = 0; i < str.length; i++) {
if (!isNaN(parseInt(str.charAt(i), 10))) {
result.push(str.charAt(i));
}
}
console.log(result);
This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 6 years ago.
I've looked up this question but am new to coding so I'm not quite able to relate other answers to this.
Given a string s, return a string
where all occurrences of its first char have
been changed to '*', except do not change
the first char itself.
e.g. 'babble' yields 'ba**le'
Assume that the string is length 1 or more.
Hint: s.replace(stra, strb) returns a version of string s
where all instances of stra have been replaced by strb.
This is what I have, but this does not replace every character after except the first, it just replaces the next character.
function fixStart(s)
{
var c = s.charAt(0);
return c + s.slice(1).replace(c, '*');
}
function fixStart(s) {
var c = s.charAt(0);
var outputStr = '';
// literate through the entire string pushing letters into a new string unless it is the first letter
for (var i = 0; i < s.length; i++) {
// if the letter is the first letter AND we are not checking the first letter
if (s[i] === c && i !== 0) outputStr += '*'
else outputStr += s[i]
}
return outputStr;
}
console.log(fixStart('hellohahaha'))
To replace all occurrences not just the first, you can use a RegExp:
function fixStart(s) {
var c = s.charAt(0);
return c + s.slice(1).replace(new RegExp(c, 'g'), '*');
}
For example if the value of c is "b", then new RegExp(c, 'g') is equivalent to /b/g.
This will work for simple strings like "babble" in your example. If the string may start with special symbols that mean something in regex, for example '.', then you will need to escape it, as #Oriol pointed out in a comment. See how it's done in this other answer.