Saturday, 19 October 2013

Replace a single character or string or multiple occurrence of a character or string in a string , JQuery

Recently I was working on my own Syntax Highlighter plugin for JQuery ( UCodeHighlighter github ) , I go through from good experience to play with strings , its characters and sub-strings.To demonstrate the string manipulations lets say we have a string :

var text='I am a programmer , I love my field and I love codding'; 

I have face following cases while working :

  • Replace a single occurrence of a string in a string :                                                                                 text= text.replace("love","very love"); // this will replace only first 'love' in above string with 'very love'
  • Replace multiple occurrence of a string in a string                                                      text= text.replace("/love/g","very love"); // this will replace both' love' in above string with 'very love'
  • Replace multiple occurrence of a dynamic string in a string                                                              var keyword='love';                                                                                                                            text= text.replace(new RegExp(keyword, 'g'),"very love"); // this will replace both' love' in above string with 'very love'
  • Replace multiple occurrence of a character in a string :                                                                                 text= text.replace(/a/g,"e"); // this will replace all 'a' characters in above string with 'e'
  • And same are the other cases for characters manipulation as strings described above.
And that's it , I hope this will help while doing your scripting :)