简体   繁体   中英

Javascript regex to convert ruby hash syntax from 1.8 to 1.9

Greetings I am trying to convert Ruby hashes from the old 1.8 style using AngularJS with a regex

{ :name => "james" }

to the newer 1.9 syntax

{ name: 'james' }

I am attempting to do this in Angular JS

with the following segment

 $scope.$watch("rubyText", function( newValue ) {
   var newVal= newValue.replace(
      new RegExp( "([\w\d_]+)(\s*)=>/\1:", "g" ),
      newValue
   );
   $scope.rubyTextConverted = newVal;   
 }

I have limited JS regex experience and would like some advice on the regular expression

Thanks

You may have to account for some edge cases like formatting, whitespace and such (unless it's scrubbed through ruby first). But to get you started here is a very basic version. You would have to add in support for Arrays and numbers and underscores. { key: [] }

var regex = /:(\w*)\s?(=>)\s?("\w*")/gi;
var string = '{ :name => "james", :lastname => "rogers" }';

string.replace(regex, "$1: $3");
 //=> '{ name: "james", lastname: "rogers" }'

Read up on back references in regex: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references

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