You need to set the g flag to replace globally:
date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')
Otherwise only the first occurrence will be replaced.
Answer from Gumbo on Stack OverflowYou need to set the g flag to replace globally:
date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')
Otherwise only the first occurrence will be replaced.
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String in as the string-to-match argument to the string.replace method, it doesn't do a string replace. It converts the string to a RegExp and does a regex substitution. As Gumbo explains, a regex substitution requires the global flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
regex - JavaScript .replace only replaces first Match - Stack Overflow
How to replace the first occurrence of a character with a string in JavaScript? - Stack Overflow
String.Replace only replaces first occurrence of matched string. How to replace *all* occurrences?
best way to replace the first occurrence of an item in an array
You need a /g on there, like this:
var textTitle = "this is a test";
var result = textTitle.replace(/ /g, '%20');
console.log(result);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You can play with it here, the default .replace() behavior is to replace only the first match, the /g modifier (global) tells it to replace all occurrences.
textTitle.replace(/ /g, '%20');
Put your replacements in a map, once a replacement is made, set map[x] to x:
let lecture = "Math";
let name = "Ex01";
let date = "2018-10-05";
let repl = {
'L': lecture,
'N': name,
'D': date
};
let file_string = "L_N_L_D"
let result = file_string.replace(/[LND]/g, x => {
let r = repl[x];
repl[x] = x;
return r;
});
console.log(result)
Apart from solving the problem at hand, this also greatly simplifies your replacement function (think adding new placeholders, for example).
That being said, a real solution to your problem would be to follow the @marsze's advice and use unambiguous placeholders, like {...}, in which case the whole enterprise becomes simply
repl = {...as before...}
result = subject.replace(/{(.+?)}/g, (_, x) => repl[x])
Answering your general question "replace only the first occurrence of a character", you could do it like this:
var lecture = "Math";
var name = "Ex01";
var date = "2018-10-05";
var found = {};
var file_string = "L_N_L_D";
var filename_result = file_string.split("").map(function (character) {
if (!found[character]) {
found[character] = true;
switch (character) {
case "L": return lecture;
case "N": return name;
case "D": return date;
}
}
return character;
}).join("");
console.log(filename_result);
You should probably explain where that odd format of the file_string comes from. Are there other similar use cases? Or is this just about this specific example? Understanding the original requirements would help a lot.
If the file_string is supposed to be a configurable format string, then it should be improved. A sequence which serves as a placeholder to be replaced should (or must) be different from a literal, e.g.:
var filename_format = "{L}_{N}_L_{D}";
In typescript, String.Replace only replaces first occurrence of matched string. Need String.replaceAll() method
There is nothing special to TypeScript here (after all TypeScript is just JavaScript with type annotations). JavaScript string.replace only replaces the first instance if given a string. Only way to get replace all is to use a regex with /g modifier.
Alternatively I just do:
somestring.split('oldString').join('newString');
In my case I did like this in TypeScript.
this.mystr= this.mystr.replace(new RegExp('class="dec-table"', 'g'), 'class="copydec-table"');
Credits to How to replace all occurrences of a string in JavaScript?
If you're not sure the item is in the list you should do:
var idx = my_list.indexOf(old_item)
if (idx !== -1) { my_list[idx] = new_item }
But else I think it's the best way to do it.
Setting a value at the index -1 won't raise an error, but will still modify the object as would setting a key in a generic js object:
var my_list = [1, 2, 3];
var old_item = 5;
var new_item = 10;
my_list[my_list.indexOf(old_item)] = new_item;
// my_list is [1, 2, 3, '-1': 10]
// my_list.length is still 3
// Object.keys(my_list) is [ '0', '1', '2', '-1' ]
So you probably don't want to do it.
Not really! There are a few ways you could do it -- one is the way you have, another is using the search method rather than indexOf, which is more versatile in that it can accept regex arguments. Note however that search is not supported in some older JS environments. There are also longer, worse ways, like using filter, or splice, but those definitely wouldn't work better.
The only suggestion I'd make is a conditional that checks whether old_item is still in the list -- indexOf returns -1 if something is not in the list, and in that case, you'll be replacing a non-existent index.
Basically, I think you're fine -- it might not be the prettiest expression, but it's about as succinct as you can get in JS.