简体   繁体   中英

How to get the value between dollar sign in string?

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?

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.

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(',');

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++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM