You can do exactly what you have :)

var string = "|0|0|0|0";
var newString = string.replace('|','');
alert(newString); // 0|0|0|0

You can see it working here, .replace() in javascript only replaces the first occurrence by default (without /g), so this works to your advantage :)

If you need to check if the first character is a pipe:

var string = "|0|0|0|0";
var newString = string.indexOf('|') == 0 ? string.substring(1) : string;
alert(newString); // 0|0|0|0​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

You can see the result here

Answer from Nick Craver on Stack Overflow
🌐
Sabe
sabe.io β€Ί blog β€Ί javascript-replace-first-occurrence-character-in-string
How to Replace the First Occurrence of a Character in a String in JavaScript | Sabe
December 9, 2022 - The easiest way to replace the first occurrence of a character in a string is to use the replace() method. ... By default, it will only replace the first occurrence of the character.
Discussions

How to replace the first occurrence of a character with a string in JavaScript? - Stack Overflow
I have a string which contains characters that should be replaced once (at first appearance). These characters are: L => will be replaced with the lecture name N => will be replaced with a name D => More on stackoverflow.com
🌐 stackoverflow.com
October 8, 2018
jquery - Why does javascript replace only first instance when using replace? - Stack Overflow
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: More on stackoverflow.com
🌐 stackoverflow.com
javascript - How to replace all BUT the first occurrence of a pattern in string - Stack Overflow
quick question: my pattern is an svg string and it looks like l 5 0 l 0 10 l -5 0 l 0 -10 To do some unittest comparison against a reference I need to ditch all but the first l I know i can ditch t... More on stackoverflow.com
🌐 stackoverflow.com
javascript - replace first occurrence of string after another string - Stack Overflow
Tried to find it in the network without any success.. Let's say I have the following string: this is a string test with a lot of string words here another string string there string here string. I More on stackoverflow.com
🌐 stackoverflow.com
July 15, 2015
Top answer
1 of 2
4

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])
2 of 2
4

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}";
🌐
Tutorial Reference
tutorialreference.com β€Ί javascript β€Ί examples β€Ί faq β€Ί javascript-how-to-replace-first-occurrence-of-character-in-string
How to Replace Only the First Occurrence of a Character in a String in JavaScript | Tutorial Reference
Replacing only the first occurrence of a character or substring in JavaScript is simple and direct. The recommended best practice is to use the string.replace('find', 'replace') method, passing a string as the first argument.
🌐
MDN Web Docs
developer.mozilla.org β€Ί en-US β€Ί docs β€Ί Web β€Ί JavaScript β€Ί Reference β€Ί Global_Objects β€Ί String β€Ί replace
String.prototype.replace() - JavaScript - MDN Web Docs
The replace() method of String values returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence ...
Author: bobbyhadz
Find elsewhere
🌐
Davidemanske
davidemanske.com β€Ί javascript-replace-only-replaces-first-occurence
JavaScript – Replace Only Replaces First Occurence
April 30, 2018 - JavaScript will only find the first instance of the target string and replace it. It will not continue to find other instances of the targeted string and replace it. Java/.Net/etc. will search for all occurrences of the target string and replace it with the replace string.
Top answer
1 of 6
40

You can try a negative lookahead, avoiding the start of the string:

/(?!^)l/g

See if online: jsfiddle

2 of 6
8

There's no JS RegExp to replace everything-but-the-first-pattern-match. You can, however, implement this behaviour by passing a function as a second argument to the replace method.

var regexp = /(foo bar )(red)/g; //Example
var string = "somethingfoo bar red  foo bar red red pink   foo bar red red";
var first = true;

//The arguments of the function are similar to $0 $1 $2 $3 etc
var fn_replaceBy = function(match, group1, group2){ //group in accordance with RE
    if (first) {
        first = false;
        return match;
    }
    // Else, deal with RegExp, for example:
    return group1 + group2.toUpperCase();
}
string = string.replace(regexp, fn_replaceBy);
//equals string = "something foo bar red  foo bar RED red pink   foo bar RED red"

The function (fn_replaceBy) is executed for each match. At the first match, the function immediately returns with the matched string (nothing happens), and a flag is set.
Every other match will be replaced according to the logic as described in the function: Normally, you use $0 $1 $2, et cetera, to refer back to groups. In fn_replaceBy, the function arguments equal these: First argument = $0, second argument = $1, et cetera.

The matched substring will be replaced by the return value of function fn_replaceBy. Using a function as a second parameter for replace allows very powerful applcations, such as an intelligent HTML parser.

See also: MDN: String.replace > Specifying a function as a parameter

🌐
DEV Community
dev.to β€Ί maafaishal β€Ί javascript-stringreplace-useful-cases-3963
JavaScript `string.replace()` useful cases - DEV Community
September 24, 2024 - Replace the first occurrence of a substring. let str = "Hello world!"; let result = str.replace("world", "JavaScript"); // Output: "Hello JavaScript!"
🌐
Mimo
mimo.org β€Ί glossary β€Ί javascript β€Ί replace
JavaScript Replace Method: Advanced String Manipulation
Master the language of the web. Learn variables, functions, objects, and modern ES6+ features ... JavaScript provides two main methods for replacing text: .replace() and .replaceAll(). .replace(): By default, it replaces only the first occurrence of a substring.
🌐
freeCodeCamp
freecodecamp.org β€Ί news β€Ί javascript-replace-how-to-replace-a-string-or-substring-in-js
JavaScript Replace – How to Replace a String or Substring in JS
November 7, 2024 - For example, using the i flag, ... console.log(newString); // Output: "I love Python and javascript loves me" In this example, the replace() method replaces the first occurrence of the word "JavaScript" with "Python" in the originalString ...
🌐
W3Schools
w3schools.com β€Ί jsref β€Ί jsref_replace.asp
JavaScript String replace() Method
The replace() method searches a string for a value or a regular expression.
🌐
Tutorial Republic
tutorialrepublic.com β€Ί faq β€Ί how-to-replace-character-inside-a-string-in-javascript.php
How to Replace Character Inside a String in JavaScript
You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ...
🌐
Vultr Docs
docs.vultr.com β€Ί javascript β€Ί examples β€Ί replace-characters-of-a-string
JavaScript Program to Replace Characters of a String | Vultr Docs
November 14, 2024 - Use the replace() method to substitute a specific character or pattern. javascript Copy Β· var originalString = "Hello World"; var modifiedString = originalString.replace("H", "J"); console.log(modifiedString); Explain Code Β· This example replaces ...
🌐
JavaScript Tutorial
javascripttutorial.net β€Ί home β€Ί javascript string methods β€Ί string.prototype.replace()
JavaScript String replace() Method
November 4, 2024 - The following example uses the replace() method to return a new string with the 'JS' replaced by 'JavaScript' in the string "JS will, JS will rock you!": let str = "JS will, JS will rock you!"; let newStr = str.replace("JS", "JavaScript"); ...
🌐
Quora
quora.com β€Ί How-do-you-replace-all-occurrences-of-a-string-in-JavaScript-Using-str-replace-only-removes-the-first-occurrence-what-should-you-do-here
How to replace all occurrences of a string in JavaScript? Using str.replace() only removes the first occurrence, what should you do here - Quora
Answer (1 of 6): I don't know it it's good practice or not, but this is what I typically use, and it gets the job done: [code]var str = "This is the original string in its original form"; str = str.split("original").join("altered"); // str = "This is the altered string in its altered form"; [...
🌐
CoreUI
coreui.io β€Ί blog β€Ί how-to-replace-all-occurrences-of-a-string-in-javascript
How to replace all occurrences of a string in JavaScript? Β· CoreUI
August 31, 2024 - ... The replace method in JavaScript is used to replace a pattern in a string with a new substring. However, by default, this method searches for the pattern and replaces only the first occurrence of it: