Javascript .replace regex alternative
One problem with your approach is (using your "new" delimiters) what happens when you get this input?
normal !@# bold &*( bold-italic !@# italic &*( normal
This would be your output:
normal <b> bold <i> bold-italic </b> italic </i> normal
And that is not valid HTML due to the crossed tags.
Instead, you need some kind of parser. A very basic one would seek out a single valid tag, and then re-parse its contents recursively. For example:
const tags = {
"!@#": "b",
"$%^": "u",
"&*(": "i",
")_+": "del"
};
const regexSanity = /[-[\]{}()*+?.,\\^$|#\s]/g; // https://stackoverflow.com/a/9310752/507674
const regex = new RegExp(
"(" + Object.keys(tags).map(
token => token.replace(regexSanity,'\\$&')
).join("|") + ")(.*?)\\1",
"g");
const parse = input=>
input.replace(
regex,
(_,tag,content) => `<${tags[tag]}>${parse(content)}</${tags[tag]}>`
);
console.log(parse("normal !@# bold &*( bold-italic !@# italic &*( normal"));
How do I replace all occurrences of a string in JavaScript?
In the latest versions of most popular browsers, you can use replaceAll
as shown here:
let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"
But check Can I use or another compatibility table first to make sure the browsers you're targeting have added support for it first.
For Node.js and compatibility with older/non-current browsers:
Note: Don't use the following solution in performance critical code.
As an alternative to regular expressions for a simple literal string, you could use
str = "Test abc test test abc test...".split("abc").join("");
The general pattern is
str.split(search).join(replacement)
This used to be faster in some cases than using replaceAll
and a regular expression, but that doesn't seem to be the case anymore in modern browsers.
Benchmark: https://jsben.ch/TZYzj
Conclusion:
If you have a performance-critical use case (e.g., processing hundreds of strings), use the regular expression method. But for most typical use cases, this is well worth not having to worry about special characters.
Replace multiple characters in one replace call
If you want to replace multiple characters you can call the String.prototype.replace()
with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping that you will use in that function.
For example, if you want a
replaced with x
, b
with y
, and c
with z
, you can do something like this:
const chars = {'a':'x','b':'y','c':'z'};
let s = '234abc567bbbbac';
s = s.replace(/[abc]/g, m => chars[m]);
console.log(s);
Output: 234xyz567yyyyxz
Alternative to replace all html entities by characters in Web Worker
My solution was to go to website that show all html entites (example: https://www.freeformatter.com/html-entities.html)
and run this code in console:
[].concat.apply([], [...document.querySelectorAll('.bordered-table')].map(table => {
var t = [...table.querySelectorAll('tbody tr')];
return t.map(tr => ({
entity: tr.querySelector('td:nth-child(2)').innerText,
char: tr.querySelector('td:nth-child(1)').innerText
})).filter(o => o.entity);
})).reduce((acc, obj) => (acc[obj.entity] = obj.code, acc), {});
then you can convert that to string using JSON.stringify(arr, true, 4);
you can copy/paste into your code and use like this:
var entities = {...}; // map from above
function renderEntities(str) {
return str.replace(/(x?)([0-9]+);/g, function(_, hex, code) {
code = parseInt(code, hex ? 16 : 10);
return String.fromCharCode(code);
}).replace(/(&[^;]+;)/g, function(_, entity) {
// if entity is not recognized it need to be
// inserted as is example &foo;
return entities[entity] || entity;
});
}
How do I replace onclick with a better alternative in vanilla javascript?
The problem with inline click attributes is that their scoping rules are very strange and unintuitive, and they require global pollution. Select the element using Javascript and use addEventListener
instead.
You can also use classList.toggle
instead of alternating between two different classes; the .block
class isn't useful because a <div>
's ordinary display
is already block
.
document.querySelector('button').addEventListener('click', () => { document.getElementById("menu").classList.toggle('hidden');});
.hidden { display: none;}.icon { fill: currentColor; height: 24px; width: 24px;}
<button> <svg class="icon" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><title>Menu</title><path d="M0 3h20v2H0V3zm0 6h20v2H0V9zm0 6h20v2H0v-2z"/></svg> </button>
<div id="menu" class="hidden"> <p>I'm no longer hidden.</p></div>
Fastest method to replace all instances of a character in a string
The easiest would be to use a regular expression with g
flag to replace all instances:
str.replace(/foo/g, "bar")
This will replace all occurrences of foo
with bar
in the string str
. If you just have a string, you can convert it to a RegExp object like this:
var pattern = "foobar",
re = new RegExp(pattern, "g");
Alternative to regexp $1 for replace
Use the following code:
var pattern = new RegExp("<div"+"(.*?)>", "g");
var text = "<div><div class='someClass'>"
text = text.replace(pattern, function(match, first_match) {
return "<pre>"+"<div>"+ first_match + ">" +"</pre>"
})
Also note that you code make your original code much neater, like so:
var pattern = new RegExp("<div"+"(.*?)>", "g");
var text = "<div><div class='someClass'>"
text = text.replace(pattern, "<pre><div>$1></pre>")
Related Topics
How to Achieve a Consistent Layout in All Browsers
Window.Scrollto Not Working in Phonegap - Alternative Solution or Workaround
Check Visibility of an Object with JavaScript
Html5 Video Custom Additional Seek Bar
Single Navigation Bar Across Website
Opening an External Website in a Modal Popup
How to Detect Which CSS Grid Column and Row an Element Is in Using JavaScript
Grunt Plugin for Assets Versioning
How to Check If Text Is Truncated by CSS Using JavaScript
Using Cookies to Retain Stylesheet Preference Across Website
How to Prevent Material Icon Text from Showing Up When Google's Js Fails to Convert Them
Screen Zooms in When a Bootstrap Modal Is Opened on iOS 9 Safari
Detect Support for Background-Attachment: Fixed
Jquery Calendar Time Selection Suggestion
How to Check That an Element Is Visible with Puppeteer and Pure JavaScript
Primefaces Dialog with Modal=True Not Working Properly
Android Web-View:Inject Local JavaScript File to Remote Webpage