I find this question really interesting. Even though I'm a little late, I would like to share my solution on how to accomplish this with regex. The solution is concise but not very readable.
While I like it for its conciseness, I probably would not use it my code, because it's opacity reduces the maintainability.
var str1 = "test xyz",
str2 = "test ab xyz"
replacement = '';
var regex = new RegExp(str1.split('').map(function(char){
return char.replace(/[.(){}+*?[|\]\\^$]/, '\\$&');
}).join('(.*)'));
if(regex.test(str2)){
for(i=1; i<str1.length; i++) replacement = replacement.concat('$' + i);
var difference = str2.replace(regex, replacement);
} else {
alert ('str2 does not contain str1');
}
The regular expression for "test xyz"
is /t(.*)e(.*)s(.*)t(.*) (.*)x(.*)y(.*)z/
and replacement
is "$1$2$3$4$5$6$7"
.
The code is no longer concise, but it works now even if str1 contains special characters.