JavaScript or Java String Subtraction

Question!

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

org.company.project.component
org.company.project.component.sub_component

you just get:

sub_component

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:

org.company.project.component.diff
org.company.project.component.sub_component

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



Answers

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++){
        thing=thing.replace(string.charAt(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 = "org.company.project.component.diff";
var b = "org.company.project.component.sub_component";
var i = 0;
while(a.charAt(i) == b.charAt(i)){
  i++;
}
alert(b.substring(i));
</script>

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