JavaScript .Replace Only Replaces First Match

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



Leave a reply



Submit