Rectangle 27 10

One new alternative that @naugtur briefly mentioned is MutationObserver. It's designed as a replacement for the deprecated mutation events, if the browser(s) you're developing for supports it (like if you're developing a browser extension).

However, Mutation Observers do not provide notification of CSS selector-based mutations though, which is a super helpful feature. I have a small module that wraps the keyframe solution above to make CSS selector listeniong even easier: github.com/csuwildcat/SelectorListener

Think @csuwldcat's advice is outdated Mutation Observers can detect any change you might infer from a CSS selector (using attributes), and more (node removal, text node changes).

@Barney a couple of things: 1) you can listen for selector matches with this method, which is impossible with Mutation Observers - for more on what this provides see: github.com/csuwildcat/SelectorListener, and 2) Mutation Observers aren't supported in older browsers like IE9, Safari 5, 6, etc.

@Barney I've updated my answer with another use-case that makes it clear what this method can do easily that Mutation Observers cannot.

javascript - Alternative to DOMNodeInserted - Stack Overflow

javascript dom firefox-addon dhtml mutation-events
Rectangle 27 39

If you are creating a web app that targets recent mobile phones and newer versions of browsers (Firefox 5+, Chrome 4+, Safari 4+, iOS Safari 3+, Android 2.1+), you can use the following code to create an awesome event for the insertion of dom nodes, and it even runs on the nodes initially part of the page's static mark-up!

Note on Mutation Observers: while the newer Mutation Observers features in recent browsers are great for monitoring simple insertions and changes to the DOM, do understand that this method can be used to do far more as it allows you to monitor for any CSS rule match you can thing of. This is super powerful for many use-cases, so I wrapped this up in a library here: https://github.com/csuwildcat/SelectorListener

@keyframes nodeInserted {  
    from {  
        outline-color: #fff; 
    }
    to {  
        outline-color: #000;
    }  
}

div.some-control {
    animation-duration: 0.01s;
    animation-name: nodeInserted;
}

This enables things that are almost impossible to do with Mutation Observers

@keyframes adjacentFocusSequence {  
    from {  
        outline-color: #fff; 
    }
    to {  
        outline-color: #000;
    }  
}

.one + .two + .three:focus {
    animation-duration: 0.01s;
    animation-name: adjacentFocusSequence;
}
document.addEventListener('animationstart', function(event){
    if (event.animationName == 'adjacentFocusSequence'){
        // Do something here when '.one + .two + .three' are 
        // adjacent siblings AND node '.three' is focused
    }
}, true);

This is by far the most excellent alternative to DOMNodeInserted I've ever seen. In fact I have been using it for months and it works well.

clip: rect
outline
insertionQuery

@naugtur outline is a good idea, especially if you can do the dummy animation on just the color. I'll probably update this thread and my blog post with that.

Sorry to say that, but now you're just confusing people. The code in your post is far from being cross-browser (animation events have prefixes, animation itself needs other prefixes) and I never said you can animate just the color. It's not what I tested.

javascript - Alternative to DOMNodeInserted - Stack Overflow

javascript dom firefox-addon dhtml mutation-events
Rectangle 27 50

Alternative with minimist

var gulp   = require('gulp');

// npm install gulp yargs gulp-if gulp-uglify
var args   = require('yargs').argv;
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');

var isProduction = args.env === 'production';

gulp.task('scripts', function() {
  return gulp.src('**/*.js')
    .pipe(gulpif(isProduction, uglify())) // only minify if production
    .pipe(gulp.dest('dist'));
});
// npm install --save-dev gulp gulp-if gulp-uglify minimist

var gulp = require('gulp');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');

var minimist = require('minimist');

var knownOptions = {
  string: 'env',
  default: { env: process.env.NODE_ENV || 'production' }
};

var options = minimist(process.argv.slice(2), knownOptions);

gulp.task('scripts', function() {
  return gulp.src('**/*.js')
    .pipe(gulpif(options.env === 'production', uglify())) // only minify if production
    .pipe(gulp.dest('dist'));
});
gulp scripts --env production

That recipe link seems gone now. There is another one that uses the minimist package instead: pass-arguments-from-cli.md. That makes sense since gulp itself uses minimist.

javascript - Is it possible to pass a flag to Gulp to have it run task...

javascript node.js gulp
Rectangle 27 38

any efficient alternative that could be used in JavaScript
any elegant solutions that would work in most, if not all, cases

There happens to be a simple, general solution that wasn't mentioned.

Compared with alternatives, the regex for this solution is amazingly simple:

"[^"]+"|(\+)

The idea is that we match but ignore anything within quotes to neutralize that content (on the left side of the alternation). On the right side, we capture all the + that were not neutralized into Group 1, and the replace function examines Group 1. Here is full working code:

<script>
var subject = '+bar+baz"not+these+"foo+bar+';
var regex = /"[^"]+"|(\+)/g;
replaced = subject.replace(regex, function(m, group1) {
    if (!group1) return m;
    else return "#";
});
document.write(replaced);

You can use the same principle to match or split. See the question and article in the reference, which will also point you code samples.

Hope this gives you a different idea of a very general way to do this. :)

The above is a general answer to showcase the technique. It can be tweaked depending on your exact needs. If you worry that your text might contain empty strings, just change the quantifier inside the string-capture expression from + to *:

"[^"]*"|(\+)

Again, the above is a general answer to showcase the technique. Not only can the "ignore this match" regex can be refined to your needs, you can add multiple expressions to ignore. For instance, if you want to make sure escaped quotes are adequately ignored, you can start by adding an alternation \\"| in front of the other two in order to match (and ignore) straggling escaped double quotes.

Next, within the section "[^"]*" that captures the content of double-quoted strings, you can add an alternation to ensure escaped double quotes are matched before their " has a chance to turn into a closing sentinel, turning it into "(?:\\"|[^"])*"

The resulting expression has three branches:

\\"
"(?:\\"|[^"])*"
(\+)

capture and handle

Note that in other regex flavors, we could do this job more easily with lookbehind, but JS doesn't support it.

\\"|"(?:\\"|[^"])*"|(\+)

This approach is actually better than the look-ahead way suggested by @Jens. It's easier to write and has much better performance. I didn't notice and used the look-ahead way until I hit a performance issue that to match a 1.5M text the look-ahead way used about 90 seconds while this approach only needed 600ms.

I found that this only worked when changing the 5th line of your example to if (group1 === undefined ) return m;. Worth noting that I was searching for spaces; not plus signs.

How would you avoid escaped quotes using this? Is it even possible with this pattern?

@BrianLow You're right. The answer was meant to demonstrate the technique in the simplest way possible. I've expanded it in response to your comment (see the "What about Empty Strings?" and "What about Escaped Quotes?" sections.

javascript - Alternative to regex: match all instances not inside quot...

javascript regex escaping quotes
Rectangle 27 37

any efficient alternative that could be used in JavaScript
any elegant solutions that would work in most, if not all, cases

There happens to be a simple, general solution that wasn't mentioned.

Compared with alternatives, the regex for this solution is amazingly simple:

"[^"]+"|(\+)

The idea is that we match but ignore anything within quotes to neutralize that content (on the left side of the alternation). On the right side, we capture all the + that were not neutralized into Group 1, and the replace function examines Group 1. Here is full working code:

<script>
var subject = '+bar+baz"not+these+"foo+bar+';
var regex = /"[^"]+"|(\+)/g;
replaced = subject.replace(regex, function(m, group1) {
    if (!group1) return m;
    else return "#";
});
document.write(replaced);

You can use the same principle to match or split. See the question and article in the reference, which will also point you code samples.

Hope this gives you a different idea of a very general way to do this. :)

The above is a general answer to showcase the technique. It can be tweaked depending on your exact needs. If you worry that your text might contain empty strings, just change the quantifier inside the string-capture expression from + to *:

"[^"]*"|(\+)

Again, the above is a general answer to showcase the technique. Not only can the "ignore this match" regex can be refined to your needs, you can add multiple expressions to ignore. For instance, if you want to make sure escaped quotes are adequately ignored, you can start by adding an alternation \\"| in front of the other two in order to match (and ignore) straggling escaped double quotes.

Next, within the section "[^"]*" that captures the content of double-quoted strings, you can add an alternation to ensure escaped double quotes are matched before their " has a chance to turn into a closing sentinel, turning it into "(?:\\"|[^"])*"

The resulting expression has three branches:

\\"
"(?:\\"|[^"])*"
(\+)

capture and handle

Note that in other regex flavors, we could do this job more easily with lookbehind, but JS doesn't support it.

\\"|"(?:\\"|[^"])*"|(\+)

This approach is actually better than the look-ahead way suggested by @Jens. It's easier to write and has much better performance. I didn't notice and used the look-ahead way until I hit a performance issue that to match a 1.5M text the look-ahead way used about 90 seconds while this approach only needed 600ms.

I found that this only worked when changing the 5th line of your example to if (group1 === undefined ) return m;. Worth noting that I was searching for spaces; not plus signs.

How would you avoid escaped quotes using this? Is it even possible with this pattern?

@BrianLow You're right. The answer was meant to demonstrate the technique in the simplest way possible. I've expanded it in response to your comment (see the "What about Empty Strings?" and "What about Escaped Quotes?" sections.

javascript - Alternative to regex: match all instances not inside quot...

javascript regex escaping quotes
Rectangle 27 37

any efficient alternative that could be used in JavaScript
any elegant solutions that would work in most, if not all, cases

There happens to be a simple, general solution that wasn't mentioned.

Compared with alternatives, the regex for this solution is amazingly simple:

"[^"]+"|(\+)

The idea is that we match but ignore anything within quotes to neutralize that content (on the left side of the alternation). On the right side, we capture all the + that were not neutralized into Group 1, and the replace function examines Group 1. Here is full working code:

<script>
var subject = '+bar+baz"not+these+"foo+bar+';
var regex = /"[^"]+"|(\+)/g;
replaced = subject.replace(regex, function(m, group1) {
    if (!group1) return m;
    else return "#";
});
document.write(replaced);

You can use the same principle to match or split. See the question and article in the reference, which will also point you code samples.

Hope this gives you a different idea of a very general way to do this. :)

The above is a general answer to showcase the technique. It can be tweaked depending on your exact needs. If you worry that your text might contain empty strings, just change the quantifier inside the string-capture expression from + to *:

"[^"]*"|(\+)

Again, the above is a general answer to showcase the technique. Not only can the "ignore this match" regex can be refined to your needs, you can add multiple expressions to ignore. For instance, if you want to make sure escaped quotes are adequately ignored, you can start by adding an alternation \\"| in front of the other two in order to match (and ignore) straggling escaped double quotes.

Next, within the section "[^"]*" that captures the content of double-quoted strings, you can add an alternation to ensure escaped double quotes are matched before their " has a chance to turn into a closing sentinel, turning it into "(?:\\"|[^"])*"

The resulting expression has three branches:

\\"
"(?:\\"|[^"])*"
(\+)

capture and handle

Note that in other regex flavors, we could do this job more easily with lookbehind, but JS doesn't support it.

\\"|"(?:\\"|[^"])*"|(\+)

This approach is actually better than the look-ahead way suggested by @Jens. It's easier to write and has much better performance. I didn't notice and used the look-ahead way until I hit a performance issue that to match a 1.5M text the look-ahead way used about 90 seconds while this approach only needed 600ms.

I found that this only worked when changing the 5th line of your example to if (group1 === undefined ) return m;. Worth noting that I was searching for spaces; not plus signs.

How would you avoid escaped quotes using this? Is it even possible with this pattern?

@BrianLow You're right. The answer was meant to demonstrate the technique in the simplest way possible. I've expanded it in response to your comment (see the "What about Empty Strings?" and "What about Escaped Quotes?" sections.

javascript - Alternative to regex: match all instances not inside quot...

javascript regex escaping quotes
Rectangle 27 11

There is one alternative to <iframe> and that's the <object> tag. It can display content from different sources as well. The pro is it being conform to the xhtml-standards and encouraged to use but there's not such a broad / usable support in older browsers (you have to mess with it to get it right in IE). It's used as followed:

<object data="page.html" width="400" height="300" type="text/html">
    Alternative Content
</object>
<iframe>
<object>

I for myself never saw an <iframe> being the cause for a slowdown, but that still might be possible. If that is an option, you should definitely try what ocanal said before in the comments: Let your script work on an wrapper container-div instead of the body-element and so embed it directly on the mainpage.

For the browser it shouldn't be much more than some overhead from handling a second document, so you could guess that it's just that little more to make your pc run slow. So it might be a good idea to optimize the code in general:

Look if you can find the bottleneck causing the slowdown. Possible causes could be

  • altering the DOM a lot - which is always slow
  • acting a lot on things not even visible on screen
  • getting attributes from objects. For every additional period you use it means more work for your cpu: // instead of using this over and over again house.roof.window.handle.open(); house.roof.window.handle.close(); // save it to a var and use that instead var handle = house.roof.window.handle; handle.open(); handle.close();
  • Updating the game in short equal intervals by window.setTimeout() may also be too fast and waste cpu power unnecessarily (or too slow and won't look fine then, but never really right) - so you can use the new window.requestAnimationFrame. The vendor-prefixed variants are implemented in the current versions of all important browsers and it's easy to provide a fallback to the old method.
  • As a last thought: Maybe it even helps in some meta-magical way to include the script file itself on the mainpage and not in the embeded document

can i use this in place of iframe in sending email via AWS?

How would one load external content using just a div?

javascript - Alternative to iframe - Stack Overflow

javascript html5 iframe
Rectangle 27 78

Actually, you can match all instances of a regex not inside quotes for any string, where each opening quote is closed again. Say, as in you example above, you want to match \+.

The key observation here is, that a word is outside quotes if there are an even number of quotes following it. This can be modeled as a look-ahead assertion:

\+(?=([^"]*"[^"]*")*[^"]*$)

Now, you'd like to not count escaped quotes. This gets a little more complicated. Instead of [^"]* , which advanced to the next quote, you need to consider backslashes as well and use [^"\\]*. After you arrive at either a backslash or a quote, you need to ignore the next character if you encounter a backslash, or else advance to the next unescaped quote. That looks like (\\.|"([^"\\]*\\.)*[^"\\]*"). Combined, you arrive at

\+(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)

Thank you! Didn't think it was possible. I understand 100% of the theory, about 60% of the regex, and I'm down to 0% when it comes to writing it on my own. Oh, well, maybe one of these days.

Hey, is there any way to make the regex work with JavaScript's .split() method? It seems to be ignoring the global flag...

?:
\+(?=(?:[^"\\]*(?:\\.|"(?:[^"\\]*\\.)*[^"\\]*"))*[^"]*$)

Tried using this in a project and it failed. I found the cause was if you had a single doublequote inside two singlequotes '"'...This would cause the number of double quotes in the string to be odd

Everyone please take a look at the solution suggested by @zx81 in his answer. That's easier to write and has much better performance if can be used.

javascript - Alternative to regex: match all instances not inside quot...

javascript regex escaping quotes
Rectangle 27 76

Actually, you can match all instances of a regex not inside quotes for any string, where each opening quote is closed again. Say, as in you example above, you want to match \+.

The key observation here is, that a word is outside quotes if there are an even number of quotes following it. This can be modeled as a look-ahead assertion:

\+(?=([^"]*"[^"]*")*[^"]*$)

Now, you'd like to not count escaped quotes. This gets a little more complicated. Instead of [^"]* , which advanced to the next quote, you need to consider backslashes as well and use [^"\\]*. After you arrive at either a backslash or a quote, you need to ignore the next character if you encounter a backslash, or else advance to the next unescaped quote. That looks like (\\.|"([^"\\]*\\.)*[^"\\]*"). Combined, you arrive at

\+(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)

Thank you! Didn't think it was possible. I understand 100% of the theory, about 60% of the regex, and I'm down to 0% when it comes to writing it on my own. Oh, well, maybe one of these days.

Hey, is there any way to make the regex work with JavaScript's .split() method? It seems to be ignoring the global flag...

?:
\+(?=(?:[^"\\]*(?:\\.|"(?:[^"\\]*\\.)*[^"\\]*"))*[^"]*$)

Tried using this in a project and it failed. I found the cause was if you had a single doublequote inside two singlequotes '"'...This would cause the number of double quotes in the string to be odd

Everyone please take a look at the solution suggested by @zx81 in his answer. That's easier to write and has much better performance if can be used.

javascript - Alternative to regex: match all instances not inside quot...

javascript regex escaping quotes
Rectangle 27 76

Actually, you can match all instances of a regex not inside quotes for any string, where each opening quote is closed again. Say, as in you example above, you want to match \+.

The key observation here is, that a word is outside quotes if there are an even number of quotes following it. This can be modeled as a look-ahead assertion:

\+(?=([^"]*"[^"]*")*[^"]*$)

Now, you'd like to not count escaped quotes. This gets a little more complicated. Instead of [^"]* , which advanced to the next quote, you need to consider backslashes as well and use [^"\\]*. After you arrive at either a backslash or a quote, you need to ignore the next character if you encounter a backslash, or else advance to the next unescaped quote. That looks like (\\.|"([^"\\]*\\.)*[^"\\]*"). Combined, you arrive at

\+(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)

Thank you! Didn't think it was possible. I understand 100% of the theory, about 60% of the regex, and I'm down to 0% when it comes to writing it on my own. Oh, well, maybe one of these days.

Hey, is there any way to make the regex work with JavaScript's .split() method? It seems to be ignoring the global flag...

?:
\+(?=(?:[^"\\]*(?:\\.|"(?:[^"\\]*\\.)*[^"\\]*"))*[^"]*$)

Tried using this in a project and it failed. I found the cause was if you had a single doublequote inside two singlequotes '"'...This would cause the number of double quotes in the string to be odd

Everyone please take a look at the solution suggested by @zx81 in his answer. That's easier to write and has much better performance if can be used.

javascript - Alternative to regex: match all instances not inside quot...

javascript regex escaping quotes
Rectangle 27 45

the example with the .innerHTML alternative:

The reason that your HTML is replaced is because of an evil JavaScript function: document.write().

It is most definitely "bad form." It only works with webpages if you use it on the page load; and if you use it during runtime, it will replace your entire document with the input. And if you're applying it as strict XHTML structure it's not even valid code.

document.write writes to the document stream. Calling document.write on a closed (or loaded) document automatically calls document.open which will clear the document.

document.write() has two henchmen, document.open(), and document.close(). When the HTML document is loading, the document is "open". When the document has finished loading, the document has "closed". Using document.write() at this point will erase your entire (closed) HTML document and replace it with a new (open) document. This means your webpage has erased itself and started writing a new page - from scratch.

document.write()

This example writes output to the HTML document after the page has loaded. Watch document.write()'s evil powers clear the entire document when you press the "exterminate" button:

I am an ordinary HTML page.  I am innocent, and purely for informational purposes. Please do not <input type="button" onclick="document.write('This HTML page has been succesfully exterminated.')" value="exterminate"/>
me!
  • .innerHTML This is a wonderful alternative, but this attribute has to be attached to the element where you want to put the text.
document.getElementById('output1').innerHTML = 'Some text!';
  • .createTextNode() is the alternative recommended by the W3C.
var para = document.createElement('p');
para.appendChild(document.createTextNode('Hello, '));
.innerHTML
I am an ordinary HTML page. 
I am innocent, and purely for informational purposes. 
Please do not 
<input type="button" onclick="document.getElementById('output1').innerHTML = 'There was an error exterminating this page. Please replace <code>.innerHTML</code> with <code>document.write()</code> to complete extermination.';" value="exterminate"/>
 me!
<p id="output1"></p>

So the evil only starts after the document is closed? Besides being unfashionable, are there any downsides to using document.write before that? Is there any practical uncertainty about when the document is closed?

@BobStein-VisiBone, yes, document.write() can be called during the page load, while the browser is parsing the page. Once the page has parsed/loaded, calling this function will also call document.open(), which wipes the page and starts from scratch. I can't think of any reason not to use the function during page load, except for consistency with the way you add content to a page any other time. And the document is closed as soon as the browser has finished parsing the document.

document.write() still seems to be the best solution to cdn local fallback. I haven't tried getElementById/innerHTML yet, but a createElement/insertBefore solution turns out to be nonsynchronous.

@Godisgood, There's no way document.write has performance problems because its the exact same function used by browsers as they load the initial HTTP response.

@Pacerier Yes, but I meant it's slower to use document.write() after the pages has loaded because it has to clear the document and then reopen it every time the function is called. .innerHTML does none of that so I'm pretty sure I read that it is faster after all. I will look for a source to back that up. I believe document.write() is fast if you use it while the page is already open.

javascript - What are alternatives to document.write? - Stack Overflow

javascript document.write
Rectangle 27 50

Here's a jQuery getScript alternative with callback functionality:

function getScript(source, callback) {
    var script = document.createElement('script');
    var prior = document.getElementsByTagName('script')[0];
    script.async = 1;

    script.onload = script.onreadystatechange = function( _, isAbort ) {
        if(isAbort || !script.readyState || /loaded|complete/.test(script.readyState) ) {
            script.onload = script.onreadystatechange = null;
            script = undefined;

            if(!isAbort) { if(callback) callback(); }
        }
    };

    script.src = source;
    prior.parentNode.insertBefore(script, prior);
}

As much as the chosen answer is clean and simple, this one is the one I will be using for the simple reason of including that callback functionality.

Any way to tell if the load failed with this?

@RubenMartinezJr. set a timeout for a couple seconds after the call and clear it on the success callback; if it fires you can probably assume it's failed (unless your source is extremely slow).

jQuery.getScript alternative in native JavaScript - Stack Overflow

javascript jquery getscript
Rectangle 27 48

Here's a jQuery getScript alternative with callback functionality:

function getScript(source, callback) {
    var script = document.createElement('script');
    var prior = document.getElementsByTagName('script')[0];
    script.async = 1;

    script.onload = script.onreadystatechange = function( _, isAbort ) {
        if(isAbort || !script.readyState || /loaded|complete/.test(script.readyState) ) {
            script.onload = script.onreadystatechange = null;
            script = undefined;

            if(!isAbort) { if(callback) callback(); }
        }
    };

    script.src = source;
    prior.parentNode.insertBefore(script, prior);
}

As much as the chosen answer is clean and simple, this one is the one I will be using for the simple reason of including that callback functionality.

Any way to tell if the load failed with this?

@RubenMartinezJr. set a timeout for a couple seconds after the call and clear it on the success callback; if it fires you can probably assume it's failed (unless your source is extremely slow).

jQuery.getScript alternative in native JavaScript - Stack Overflow

javascript jquery getscript
Rectangle 27 3

In modern (ES2015) JavaScript you can use Array.from():

Array.from(arguments).forEach((arg) => {
  this.score += arg;
});

You don't need to use array indexing, as the .forEach() function passes each array element to the callback function as the first argument. (It does pass the index as the second argument, but in this case you wouldn't need to use that.)

It's important to note that if the arguments object is passed out of a function (as it would be here), the overall function may be considered ineligible for optimization. That's because the arguments object has some weird properties that make it very hard for the optimizer to know what's going on and whether it's safe to make assumptions about how local variables change. If that's a concern, then the only option is to copy the arguments into a simple array with a for loop.

This was very helpful! It worked. 7 more minutes before I can check it. Thanks!

javascript - alternative to for loop - Stack Overflow

javascript arrays node.js oop
Rectangle 27 13

Javascript is a very flexible language in this regard. There are very very few cases where eval() is the right answer to any given question, and it certainly isn't necessary here.

ie myobj.a could also be referenced as myobj['a'].

From that, you can use a variable for the subscript, and thus you can reference any element in myobj dynamically -- ie:

var myobj = {a : 5, b : 10};

var dynamicProperty1 = 'a';
var dynamicProperty2 = 'b';

//gives 15.
alert( myobj[dynamicProperty1] + myobj[dynamicProperty2] );

No eval() required. You can build the dynamicProperty strings however you wish, so there's virtually infinite flexibility.

If your a and b variables are globals, JS globals in the browser are actually children of the window object, so you can still use this technique even with globals.

ie your global variable a could also be accessed via window.a or window['a'], with the latter option allowing you to do the same dynamicProperty trick described above.

jquery - Alternative to eval() javascript - Stack Overflow

javascript jquery jquery-plugins eval
Rectangle 27 1131

Note: Don't use this in real 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("");
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. So, this should really only be used as a quick hack to avoid needing to escape the regular expression, not in real code.

It surprised me, as I would expect this method to be allocating more objects, creating more garbage, and thus take longer, but when I actually tested in a browser this method was consistently about 20% faster than the accepted response. Results may vary, of course.

I was curious myself, and set up this: jsperf.com/replace-all-vs-split-join . It seems that v8 is just crazy fast at splitting/joining arrays compared to other javascript engines.

Very nice - also saves you from the possibility of bad RegExps when passing in special characters. I'm adding in a generic flag for "find this and replace it" in an object property, but was concerned if I needed to replace "." or "}" and forgot I was using RegEx 3 months later!

String.prototype.replaceAll = function(f,r){return this.split(f).join(r);}
"My string".replaceAll('st', '');

How to replace all occurrences of a string in JavaScript? - Stack Over...

javascript replace
Rectangle 27 1128

Note: Don't use this in real 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("");
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. So, this should really only be used as a quick hack to avoid needing to escape the regular expression, not in real code.

It surprised me, as I would expect this method to be allocating more objects, creating more garbage, and thus take longer, but when I actually tested in a browser this method was consistently about 20% faster than the accepted response. Results may vary, of course.

I was curious myself, and set up this: jsperf.com/replace-all-vs-split-join . It seems that v8 is just crazy fast at splitting/joining arrays compared to other javascript engines.

Very nice - also saves you from the possibility of bad RegExps when passing in special characters. I'm adding in a generic flag for "find this and replace it" in an object property, but was concerned if I needed to replace "." or "}" and forgot I was using RegEx 3 months later!

String.prototype.replaceAll = function(f,r){return this.split(f).join(r);}
"My string".replaceAll('st', '');

How to replace all occurrences of a string in JavaScript? - Stack Over...

javascript replace
Rectangle 27 1128

Note: Don't use this in real 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("");
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. So, this should really only be used as a quick hack to avoid needing to escape the regular expression, not in real code.

It surprised me, as I would expect this method to be allocating more objects, creating more garbage, and thus take longer, but when I actually tested in a browser this method was consistently about 20% faster than the accepted response. Results may vary, of course.

I was curious myself, and set up this: jsperf.com/replace-all-vs-split-join . It seems that v8 is just crazy fast at splitting/joining arrays compared to other javascript engines.

Very nice - also saves you from the possibility of bad RegExps when passing in special characters. I'm adding in a generic flag for "find this and replace it" in an object property, but was concerned if I needed to replace "." or "}" and forgot I was using RegEx 3 months later!

String.prototype.replaceAll = function(f,r){return this.split(f).join(r);}
"My string".replaceAll('st', '');

How to replace all occurrences of a string in JavaScript? - Stack Over...

javascript replace
Rectangle 27 1182

Another alternative with .lastIndexOf:

haystack.lastIndexOf(needle, 0) === 0

This looks backwards through haystack for an occurrence of needle starting from index 0 of haystack. In other words, it only checks if haystack starts with needle.

haystack
  • It doesn't create a new temporary string and then immediately discard it.

Not sure which case @rfcoder89 is taking about - jsfiddle.net/jkzjw3w2/1

@rfcoder89 Notice the second parameter of lastIndexOf: "aba".lastIndexOf ("a") is 2 as you point out, but "aba".lastIndexOf ("a", 0) is 0, which is correct

Thank you so much. String.startsWith does not work on Android lollipop WebView, but this lastIndexOf snippet does!!!

with lastIndexOf the string is searched from the end to the beginning so it searches the whole string: so its inefficiency grows for very long strings to search in.

@willywonka No, it's not if you have 0 startIndex, it is searched from 0 pos and it's the only check. The whole string is searched only if fromIndex >= str.length.

javascript - How to check if a string "StartsWith" another string? - S...

javascript string startswith
Rectangle 27 1172

Another alternative with .lastIndexOf:

haystack.lastIndexOf(needle, 0) === 0

This looks backwards through haystack for an occurrence of needle starting from index 0 of haystack. In other words, it only checks if haystack starts with needle.

haystack
  • It doesn't create a new temporary string and then immediately discard it.

Not sure which case @rfcoder89 is taking about - jsfiddle.net/jkzjw3w2/1

@rfcoder89 Notice the second parameter of lastIndexOf: "aba".lastIndexOf ("a") is 2 as you point out, but "aba".lastIndexOf ("a", 0) is 0, which is correct

Thank you so much. String.startsWith does not work on Android lollipop WebView, but this lastIndexOf snippet does!!!

with lastIndexOf the string is searched from the end to the beginning so it searches the whole string: so its inefficiency grows for very long strings to search in.

@willywonka No, it's not if you have 0 startIndex, it is searched from 0 pos and it's the only check. The whole string is searched only if fromIndex >= str.length.

javascript - How to check if a string "StartsWith" another string? - S...

javascript string startswith