1

I searched through the online resources i found for this particular quest, but im stuck with something that i couldn't get help through them. I'm trying to find a way to add style to the first matched letter in an array and discard the remaining matched letters.eg say I have a search string called: "disabledDouble". I use the split() method on the string to separate the matched element from the unmatched ones:

search: function(){
 var search = "d";
 var string = "disabledDouble";
 var regex = new RegExp("(" + search + ")", "gi");
 var segments = string.split(regex); //o/p :["d", "isable", "d","D","ouble"]
 return (
      //styled element <span>
    )

}

now i want to just add style to the first 'd' in the array (not worry about the second or third 'd's') and join the remaining string such that o/p becomes:

disabledDouble

similarly since the string is dynamically created I've values like:

showStability

accessValues

In all the above cases I'd like to add style only to the first matched value. any ideas???

sarah
  • 37
  • 6
  • your question is quite unclear, would you like to treat the first character or do you need to searchg fo a special pttern an change the something? if you only want to change the first character of a string, you could use replace instead. – Nina Scholz Aug 30 '16 at 17:54
  • To my knowledge, you can't style individual characters with CSS. You'd need to wrap them in their own elements such as spans and apply the styling that way. See this http://stackoverflow.com/questions/24705721/nth-letter-why-is-it-not-working for more details. – War10ck Aug 30 '16 at 17:54

2 Answers2

0

You can use replace

var search = "d";
var string = "disabledDouble"
var regex = new RegExp(search, "i");
console.log(string.replace(regex, function(a) {return "<span>" + a + "</span>";}));
001
  • 13,291
  • 5
  • 35
  • 66
  • isnt there a way not to have that while returning the o/p..: i tried adding class to span and stylizing it..doesnt work... in the o/p returns showStatus https://jsfiddle.net/xzug4yns/ – sarah Aug 30 '16 at 18:12
  • I'm not sure. You need the span (or strong like in other answer). Like this: https://jsfiddle.net/xzug4yns/1/ – 001 Aug 30 '16 at 18:21
0

Suppose, you want to change the first character only.

var string = 'abracadabra';

console.log(string.replace(/./, '<strong>$&</strong>'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • well..i want to style the character depending on the search string value...if the value in the searchfield is "a", I get a list of words having letter "a" in them:eg: value,access,allowance..in all the cases I would just like to style the first occurance of "a" appearing in the word..eg in "allowance", style only allowance. hope this one is clear – sarah Aug 30 '16 at 18:20
  • please add the use cases to your question. but it's still not clear for me, what you want. – Nina Scholz Aug 30 '16 at 18:21