How to replace the second occurrence of a string in javascript [duplicate] - javascript

This question already has answers here:
Simple Javascript Replace not working [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to replace the second occurrence of a string in javascript. I'm using a regex to detect all the matches of the character that I'm looking for. The alert returns the same initial text.
text = 'BLABLA';
//var count = (texte.match(/B/g) || []).length;
var t=0;
texte.replace(/B/g, function (match) {
t++;
return (t === 2) ? "Z" : match;
});
alert(text);
https://js.do/code/157264

It's because you never use the result returned by the replace function.
Here's the corrected code:
const text = 'BLABLA'
let t = 0
const result = text.replace(/B/g, match => ++t === 2 ? 'Z' : match)
console.log(result)

Related

Using Regex as conditional in Javascript [duplicate]

This question already has answers here:
How to check if character is a letter in Javascript?
(17 answers)
Closed 3 years ago.
Hello I am having trouble trying to use Regex to check if each character in string is an alphabet.
First let me introduce the problem itself.
There is a string mixed with special chars and alphabets and suppose to return the number of alphabets only.
My code/pseudo code for problem is :
//Create var to hold count;
var count = 0;
//Loop thru str
for(let char of str){
//Check if char is a alphabet
***if(char === /[A-Za-z]/gi){***
//if so add to count
count ++;
}
//return count;
return count;
}
How can I use Regex in a conditional statement to check if each char is an alphabet????
Please help!
const pattern = /[a-z]/i
const result = [...'Abc1'].reduce((count,c) => pattern.test(c) ? count+1 : count, 0)
console.log(result) // 3

RegEx for checking multiple matches [duplicate]

This question already has answers here:
How can I match overlapping strings with regex?
(6 answers)
Closed 3 years ago.
I want to match all occurrence in string.
Example:
pc+pc2/pc2+pc2*rr+pd
I want to check how many matched of pc2 value and regular expression is before and after special character exists.
var str = "pc+pc2/pc2+pc2*rr+pd";
var res = str.match(new RegExp("([\\W])pc2([\\W])",'g'));
But I got only +pc2/ and +pc2* and /pc2+ not get in this.
Problem is in first match / is removed. So after that, it is starting to check from pc2+pc2*rr+pd. That's why /pc2+ value does not get in the match.
How do I solve this problem?
You need some sort of recursive regex to achieve what you're trying to get, you can use exec to manipulate lastIndex in case of value in string is p
let regex1 = /\Wpc2\W/g;
let str1 = 'pc+pc2/pc2+pc2*rr+pd';
let array1;
let op = []
while ((array1 = regex1.exec(str1)) !== null) {
op.push(array1[0])
if(str1[regex1.lastIndex] === 'p'){
regex1.lastIndex--;
}
}
console.log(op)

Javascript replace regex using [duplicate]

This question already has answers here:
Removing Numbers from a String using Javascript
(2 answers)
Closed 3 years ago.
I need to change #x ( x a number) to x.
How can I do that, I don't know js regex..
You can try like this.
var n = Number(s.replace(/\D+/, ''))
> var s = "#123";
undefined
>
> var n = s.replace(/\D+/, '')
undefined
>
> n
'123'
>
> n = Number(n)
123
>
> n + 7
130
>
Just use replace like so:
const str = "#1235";
const num = str.replace("#", "");
console.log(num);
You can use inbuilt replace function for this purpose, which can take both, literals and regex pattern as parameter.
var str = "#12345";
str.replace("#", "");
We can also use patterns in the replace parameter, if you have multiple values to be replaced.
var str = "#123#45";
str.replace(/[##]/,"") // prints "123#45" => removes firs occurrence only
str.replace(/[##]/g,"") // prints "12345"
str.replace(/\D/,"") // prints "123#45" => removes any non-digit, first occurrence
str.replace(/\D/g,"") // prints "12345" => removes any non-digit, all occurrence
g stands for global search
[##] stands for either # or #, you can add anything here
\D stands for anything other than digits

Replace nth occurence of number in string with javascript [duplicate]

This question already has answers here:
Find and replace nth occurrence of [bracketed] expression in string
(4 answers)
Closed 5 years ago.
This question been asked before, but I did not succeed in solving the problem.
I have a string that contains numbers, e.g.
var stringWithNumbers = "bla_3_bla_14_bla_5";
I want to replace the nth occurence of a number (e.g. the 2nd) with javascript. I did not get farer than
var regex = new RegExp("([0-9]+)");
var replacement = "xy";
var changedString = stringWithNumbers.replace(regex, replacement);
This only changes the first number.
It was suggested to use back references like $1, but this did not help me.
The result should, for example, be
"bla_3_bla_xy_bla_5" //changed 2nd occurence
You may define a regex that matches all occurrences and pass a callback method as the second argument to the replace method and add some custom logic there:
var mystr = 'bla_3_bla_14_bla_5';
function replaceOccurrence(string, regex, n, replace) {
var i = 0;
return string.replace(regex, function(match) {
i+=1;
if(i===n) return replace;
return match;
});
}
console.log(
replaceOccurrence(mystr, /\d+/g, 2, 'NUM')
)
Here, replaceOccurrence(mystr, /\d+/g, 2, 'NUM') takes mystr, searches for all digit sequences with /\d+/g and when it comes to the second occurrence, it replaces with a NUM substring.
var stringWithNumbers = "bla_3_bla_14_bla_5";
var n = 1;
var changedString = stringWithNumbers.replace(/[0-9]+/g,v => n++ == 2 ? "xy" : v);
console.log(changedString);

Count number of times a character appears in string [duplicate]

This question already has answers here:
Count number of occurrences for each char in a string
(23 answers)
Closed 6 years ago.
So basically I need a script that summarizes which characters and the number of times they appear in a random string. Caps have to be ignored, for example:
var myString = promt ("Type anything: "); //"hello Hello";
The end result has to be something like this: h = 2, e = 2, l = 4, o = 2 printed in the HTML document.
I've tried using myString.match().length without much success. My main problem is defining which characters to check and not checking characters twice (for example: if there are two "h" in the string not checking them twice).
You can use temporary object
var o = {};
"hello Hello".toLowerCase()
.replace(/\s+/, '')
.split('')
.forEach(e => o[e] = ++o[e] || 1);
document.write(JSON.stringify(o));
This solution uses arrow function (ES2015 standard) that doesn't work in old browsers.
var str = 'hello Hello';
var count = {};
str.split('').forEach(function(v) {
if (v === ' ') return;
v = v.toLowerCase();
count[v] = count[v] ? count[v] + 1 : 1;
})
console.log(count);

Categories

Resources