1

I am trying to get the value between dollar sign in a string and put them in a list.

For example, here is a string:

var a ='Dear $name$, This is my number $number$. This is my address $address$ Thank you!'

and what I want to get is,

var b = '$name$,$number$,$address$'

Do I have to take care about the '$' in the string due to $ is also used in jQuery? Do you have any idea about it?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Hailei
  • 39
  • 5
  • Can you post what you've tried so far and what's not working in your attempts? – Melissa Avery-Weir Apr 16 '15 at 17:20
  • 1
    You want to be careful about `$` because it has special meaning in regular expressions. Nothing in the question, or the answers, has anything to do with jQuery. This is a plain-Javascript question. – Paul Roub Apr 16 '15 at 17:25

3 Answers3

11

Use match:

a.match(/\$.*?\$/g);

This returns an array with all the values. You can also use

a.match(/\$.*?\$/g)||[];

to make sure that you’ve always got an array because if there’s no match you’ll get the null object which is not always useful.

The RegExp is also explained in an answer of mine to a similar question: match anything (.), any number of times (*), as few times as possible (?).

Then you can use join to join that Array into a String:

(a.match(/\$.*?\$/g)||[]).join(',');

Code:

var a='Dear $name$, This is my number $number$. This is my address $address$ Thank you!';
var b=(a.match(/\$.*?\$/g)||[]).join(',');

Output:

"$name$,$number$,$address$"

Effectively, in this case the regular expression matches every $ followed by anything up to the next $ and finally that dollar sign at the end. And match will give a list of results if you specify the g (global) flag at the end.

As this is a string (and the above a regular expression) literal, there’s no interference with jQuery’s $ symbol. The only important thing is to escape that symbol with a backslash (\$) because it has a special meaning in RegExp.

Community
  • 1
  • 1
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
0

get matches with a regular expression:

var matches = a.match(/\$\w+\$/g);

returns an array of matches, so then just join on comma:

var b = matches.join(',');
Austin Greco
  • 32,997
  • 6
  • 55
  • 59
0

Essentially you need to split and slice. I made a JSFiddle to show how its done.

Here is the jQuery to accomplish what you want.

var a = 'Dear $name$, This is my number $number$. This is my address $address$ Thank you!';

var b = [];
var count = 0;

var split = a.split(" ");
for (var i = 0; i < split.length; i++) {
    if (split[i].charAt(0) == "$") {
        b[count] = split[i].slice(0, $.inArray("$", split[i], 2)) + "$";
        count++;
    }
}
ManicComputer
  • 221
  • 2
  • 6