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. Javascript .replace only replaces first occurrence
Got it to work by using .replaceAll()
(as suggested by @ouroboring)
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 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,"%%");
Replacing only the first match of a global regex
It would seem that the best way to do this would be to just manually remove the g
flag from the regex. Here's the most cross-platform way I could find to do this, using regex.toString()
to get the string representation of the regex:
function recursiveReplace(string, regex, replacement) {
regex = eval(regex.toString().replace(/[a-z]*$/, function (s) {
return s.replace('g', '');
}));
for (var i = 1e8; i > 0 && regex.test(string); i--)
string = string.replace(regex, replacement);
return string;
}
With the ES6 features RegExp(regex)
and RegExp#flags
this gets much easier:function recursiveReplace(string, regex, replacement) {
regex = RegExp(regex, regex.flags.replace('g', ''));
for (var i = 1e8; i > 0 && regex.test(string); i--)
string = string.replace(regex, replacement);
return string;
}
Javascript Regex only replacing first match occurence
^=+|=+$
You can use this.Do not forget to add g
and m
flags.Replace by ``.See demo.http://regex101.com/r/nA6hN9/28
Related Topics
Efficient Way to Insert a Number into a Sorted Array of Numbers
How to Show Current Time in JavaScript in the Format Hh:Mm:Ss
Converting a Buffer into a Readablestream in Node.Js
What Is Ngdefaultcontrol in Angular
How Does Internationalization Work in JavaScript
Jsf/Primefaces Ajax Updates Breaks Jquery Event Listener Function Bindings
Javascript: Dynamically Creating Variables for Loops
JavaScript Contenteditable - Set Cursor/Caret to Index
Subject VS Behaviorsubject VS Replaysubject in Angular
Unexpected Token Illegal in Webkit
Single Quote Escape in JavaScript Function Parameters
Create a <Ul> and Fill It Based on a Passed Array
Scope of Default Function Parameters in JavaScript
Angularjs Does Not Send Hidden Field Value
How Do Print the Console Output of the Page in Puppeter as It Would Appear in the Browser