Why does javascript replace only first instance when using replace?
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.
JavaScript .replace only replaces first Match
You need a /g
on there, like this:
var textTitle = "this is a test";var result = textTitle.replace(/ /g, '%20');
console.log(result);
Replace only replacing the first
To perform a global replacement you can use g
:
Try this
callback($(this).prop('title').replace(/\|/g, '<br />'));
More infor is HERE.
why does str.replace() only replace the first found item?
Add the global selection "g" flag and use a regex instead of a string in first parameter.
result = text.replace(/\//g, "");
javascript replace function only replaces the first occurance
Try using regex /g
.replace(/'/g,"%%")
Change your code as below,
document.getElementById("Message").innerHTML =
document.getElementById("Message")
.innerHTML
.replace(/'/g,"%%");
Javascript .replace only replaces first occurrence
Got it to work by using .replaceAll()
(as suggested by @ouroboring)
regex replace only the first occurrence of every match
[^"]*
will try to match all possible matches.
Use non-greedy/lazy regex
/(href=")[^"]*?(\/3)/
^
|
Regex Demo
var toReplace = 'href="/3" href="/3/a" href="a/3" href="h/3/a/3/b"';var replacedString = toReplace.replace(/(href=")[^"]*?(\/3)/gi, '$1*');
document.write(replacedString);
Related Topics
Should I Use Window.Navigate or Document.Location in JavaScript
:Touch CSS Pseudo-Class or Something Similar
Convert Relative Path to Absolute Using JavaScript
How to Get Old Value with Onchange() Event in Text Box
How to Separate Web Components to Individual Files and Load Them
Detect Click Event Inside Iframe
How to Save and Restore a File Object in Local Storage
Opening New Window in HTML for Target="_Blank"
Any Event Triggered on Autocomplete
How to Get File Name When User Select a File via <Input Type="File" />
How to Pass Along Variables with Xmlhttprequest
Perform Action When Clicking HTML5 Datalist Option
Change Value of Input and Submit Form in JavaScript
How to Play a Notification Sound on Websites
JSON.Stringify Output to Div in Pretty Print Way
Open Url in New Tab or Reuse Existing One Whenever Possible