0

I have such simple example. I want to replace text in for example add ann.c same way I replace it in add Ann.c. How to do it with jQuery?

Here is how I've done it: $("#tags").val().replace(dictionary[j]['name'].toLowerCase(), dictionary[j]['realvalue']); Sorry for bothering... but any more optimal solutions are much welcome.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Rella
  • 65,003
  • 109
  • 363
  • 636
  • 1
    possible duplicate: http://stackoverflow.com/questions/280793/case-insensitive-string-replacement-in-javascript – keks Aug 13 '11 at 22:29

3 Answers3

3

Use String.replace() with a regexp object that has the i (case-insensitive) flag set.

You can safely build a regexp object from an arbitrary string provided that you escape that string first.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
2
$("#tags").val().toLowerCase(); // will convert all uppercase characters to lowercase ones

Then it looks for e.g. ann.c so you'd need to alter the object:

var dictionary = jQuery.parseJSON('[ { "name": "ann.c",  "realvalue": "./34534j435345j3b3"  }, {   "name": "ann.h",   "realvalue": "./333dfsdGjh45j3b5" }]');

By the way what about:

var dictionary = [ { "name": "ann.c",  "realvalue": "./34534j435345j3b3" },
                   { "name": "ann.h",  "realvalue": "./333dfsdGjh45j3b5" } ];

http://jsfiddle.net/pimvdb/uDdbq/18/

pimvdb
  • 151,816
  • 78
  • 307
  • 352
1
var text = $("#tags").val().replace(RegExp(dictionary[j]['name'],"i"), dictionary[j]['realvalue']);

you can convert the string to a regex and add case insensitive to it.

Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129