pookie
pookie

Reputation: 4142

Find partial match in string

I have the following string:

http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=1|4093F6|FFFFFF

I would like to find the chld=1.

The 1 could be any number and I need to change it.

How can I find chld=x where x stands for any number?

Upvotes: 4

Views: 688

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627469

Here is a possible way:

var re = /chld=\d+/; 
var str = '"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=1|4093F6|FFFFFF"';
document.getElementById("res").innerHTML = str.replace(re, "chld=100");
<div id="res"/>

The regex is chld=\d+ which is very basic:

  • chld= - Matches literal chld= string
  • \d+ - Matches 1 or more digits.

In case you have multiple chlds, and you want to set them with the same value, just add g flag to var re = /chld=\d+/g;. As an alternative to using \d you can achieve the same with [0-9] character range: var re = /chld=[0-9]+/g;. However, in JavaScript, \d and [0-9] are equal:

Since certain character classes are used often, a series of shorthand character classes are available. \d is short for [0-9]. In most flavors that support Unicode, \d includes all digits from all scripts. Notable exceptions are Java, JavaScript, and PCRE. These Unicode flavors match only ASCII digits with \d.

Upvotes: 4

Related Questions