tags:

views:

86

answers:

4

I have two strings:

var str1 = '8***8***';
var str2 = '898-8293';

How can i wrap the digits found in string one, with html elements on the second string, like so:

'<b>8</b>98-<b>8</b>293'

Note: Not all '8' digits are wrapped.

[EDIT]

Thanks to Soufiane Hassou and voyager the following worked:

<script type="text/javascript">
var str1 = '8***8***';
var str2 = '898-8293';

var result = [];

var arr1 = str1.split('');
var arr2 = str2.split('');

for (var i = 0; i < arr2.length; i++) {
    if (arr1[i] == arr2[i]) {
     result.push('<b>' + arr2[i] + '</b>');
    }
    else {
     result.push(arr2[i]);
    }
}

var newStr = result.join('');
</script>
A: 
var result='';
for(int i = 0; i < str2.length; i++) {
   if(str2[i] == str1[i] {
      result+='<b>' + str1[i] + '</b>';
   }
   else {  result+=str2[i]; }

}

Is this what you want to do?

Soufiane Hassou
This doesn't work in IE6, because you can't treat a string like an array.
goyo
A: 
highlight_string = function(str, mask){

    var result='';
    str1 = mask.split("");
    str2 = str.split("");
    for(int i = 0; i < str2.length; i++) {
       if((str1[i] == "*") || (str2[i] == str1[i])) {
          result+='<b>' + str1[i] + '</b>';
       }
       else {  result+=str2[i]; }
    }
    return result;
}

Expanding on Soufiane Hassou's answer, I think this is closer to what you are looking for.

voyager
Thanks, the split method made the difference.
goyo
The initializing statement in the `for` loop should be `var i = 0` conditional statement in the for loop should be `(str1[i] != "*") || (str2[i] == str1[i])`, not `(str1[i] == "*") || (str2[i] == str1[i])`. This would work, but a Regular Expression based solution would be more flexible, as this depends on users entering a search statement the same length as the statement being searched, although it looks like the question has been edited to negate that problem.
Ryan Lynch
Thanks Ryan, I implemented those changes already. And I have a different function that makes both strings same length, adding * where needed.
goyo
A: 

It looks like you are actually trying to do isn't combine the two strings, but to match a regular expression in str1 to a value in str2. If that's the case you would want to change str1 a regular expression and test str2 against it. Something like this:

/[8]\d{2}[-][8]\d{3}/.test('898-8293');
//or
/[8]\d*[-][8]\d*/.test('898-8293');
//or
/[8].*[-][8].*/.test('898-8293');
//or
/[8].*[8].*/.test('898-8293');
Ryan Lynch
Yeah, but he wants to highlight the matching section of the original string too.
voyager
In that case you would have to split the user input string and process them in a loop as a series of regular expressions to determine the explicitly matched strings and the intermediate wildcard strings.
Ryan Lynch
A: 
var str2 = '898-8293';
var str3 = str2.replace(/(\d{1})(\d{2})(-)(\d{1})(\d{3})/g, '<br>$1</br>$2$3<br>$4</br>$5');
alert(str3);

For the win.

KennyBastani