JavaScript or Java String Subtraction


If you are using Java or JavaScript, is there a good way to do something like a String subtraction so that given two strings:

you just get:


I know that I could just write code to walk the string comparing characters, but I was hoping there was a way to do it in a really compact way.

Another use-case is to find the diff between the strings:

I actually only want to remove the sections that are identical.


This is a solution for the Javascript end of the question:

String.prototype.contracat = function(string){
    var thing = this.valueOf();
    for(var i=0; i<string.length;i++){
    return thing

function sub(a, b) {
  return [a, b].join('\x01').match(/^([^\x01]*)[^\x01]*\x01\1(.*)/)[2];

Though this relies on that the character with code 1 does not appear in any of those strings.

At first glance, I thought of RegExp, but adding to the question, you removed that possibility by adding to the start-string ...

So you'll have to make a procedure, that takes every character that are equal out of the resulting string, something like this:

<script type="text/javascript">
var a = "";
var b = "";
var i = 0;
while(a.charAt(i) == b.charAt(i)){

By the way it doesn't have a meaning to set Java and javascript as equals in any context, a popular way of putting it could be:

Java and javascript has four things in common: j - a - v - a !-)

By : roenving

This video can help you solving your question :)
By: admin