2017-10-06 18 views
1

我正在尋找一個函數,將命名空間的字符串,例如,如果我想與「MyLib中」來命名空間下面的字符串,如何命名空間的字符串(例如。'a(x)+ b'=>'Namespace.a(x)+ Namespace.b')

"select('#input') + someconstant * otherconstant" 

將改爲

"MyLib.select('#input') + MyLib.someconstant * MyLib.otherconstant" 

BTW它需要一個字符串作爲輸入,並返回另一個字符串

我之所以想要這樣做是因爲我正在編寫一個用戶界面wh ICH與另一個庫定製數學函數比較我自定義的數學函數,例如用戶可以鍵入

"factorial(2) + sin(intpow(2, 4))" 

這將被轉換爲

"MyCustomLib.factorial(2) + MyCustomLib.sin(MyCustomLib.intpow(2, 4))" 
/* and */ 
"OtherLib.factorial(2) + OtherLib.sin(OtherLib.intpow(2, 4))" 

,然後我可以使用eval()來評估它(不要對我使用eval就擔心,擔心的問題:))

我目前的函數看起來像

const namespace = (str, ns) => { 
    ns = ns + '.'; // add the dot to the namespace 
    let s = String(str), 
     m, // the result of regex 
     re = /\w+/g, // only namespace words 
     a = 0; // because there are two strings, and i am 
      // only adding to one of them, 
      // i have to increase the index to make up for 
      // the difference between the two 
    while ((m = re.exec(str)) !== null) { // until there is no more words 
    // get the new string (put the namespace in) 
    // eg. "(junk) abc (junk)" => "(junk) Namespace.abc (junk)" 
    s = s.slice(0, m.index + a) + ns + s.slice(m.index + a); 
    a += ns.length; // add to the offset 
    } 
    return s; // return the parsed string 
}; 

其中,param STR是輸入字符串,和param ns是命名空間

它的工作原理,即。

namespace("PI * sin(E)", "Math") === "Math.PI * Math.sin(Math.E)" 

但它不完全工作,即

namespace("23", "abc"); /* === "abc.23" */ 

當它應該不是等於 「23」

什麼想法?

回答

-1

您可以使用re = /[A-z]+/g,僅僅映射字母字符

+0

這是不行的,什麼是「abc234」?變量可以以數字結尾 –

+0

嗯,哇感謝鼓舞我!我猜 –

+0

/[a-zA-Z] \ w */g的作品 –

相關問題