Rella
Rella

Reputation: 66995

How to Find and replace parts of string in case insensitive way?

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.

Upvotes: 0

Views: 595

Answers (3)

Matt Ball
Matt Ball

Reputation: 360066

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.

Upvotes: 3

pimvdb
pimvdb

Reputation: 154968

$("#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/

Upvotes: 2

Joseph Marikle
Joseph Marikle

Reputation: 78590

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.

Upvotes: 1

Related Questions