Why Does JavaScript Replace Only First Instance When Using Replace

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



Leave a reply



Submit