2017-10-06 1 views
1

문자열을 네임 스페이스로 지정할 함수를 찾고 있습니다.문자열을 네임 스페이스하는 방법 (예 : 'a (x) + b'=> 'Namespace.a (x) + Namespace.b')

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

이 BTW

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

이 다른 문자열

이유 I를 입력으로 문자열을 받아, 반환로 변경됩니다 "MYLIB"로 다음 문자열을 네임 스페이스 싶어 내가 사용자 인터페이스 wh를 쓰고 있기 때문에 이렇게하고 싶습니다. (사용자가

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

로 변환 될 수

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

를 입력 할 수 있습니다 그리고 내가 그것을 평가하는 평가를()를 사용할 수 있습니다 예를 들어 무형 문화 유산은 다른 라이브러리 사용자 정의 수학 함수 내 사용자 정의 수학 함수를 비교) : 질문에 대해 걱정 나를 평가 사용에 대한 걱정을하지 말아

내 현재 기능은

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 
}; 
0123처럼 보인다 PARAM STR 입력 문자열을, 그리고 PARAM ns 네임 스페이스

작동, 즉이다

.

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

하지만 완전히 즉

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

, 때해야하는 대신 동일한 "23"

어떤 아이디어를 작동 나던?

답변

-1

당신은 무엇을 "abc234"에 대한 문제가 해결되지에만 알파벳 문자

+0

를 매핑 할 re = /[A-z]+/g,를 사용할 수 있습니까? 변수는 숫자로 끝나야합니다 –

+0

흠, 저에게 영감을 주신 데 대해 감사드립니다! 제 생각에 –

+0

/[a-zA-Z] \ w */g가 작동합니다 –

관련 문제