stringTest.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * Created by Tony on 2017/6/21.
  3. */
  4. /**
  5. * Created by Tony on 2017/6/21.
  6. */
  7. var test = require('tape');
  8. test('string test1', function(t){
  9. let str = "at('1.1') + at('1.2') + at('1.3') + at('1.4')";
  10. //let re = /at(/g;
  11. //let re = new RegExp("at\(", "g");
  12. //let str1 = str.replaceAll('re', '@(');
  13. //let str1 = str.replace('at(', '@(');
  14. var str1 = str.split('at1(').join('@(');
  15. //t.equal(str1, "@('1.1') + @('1.2') + @('1.3') + @('1.4')");
  16. t.equal(str1, "at('1.1') + at('1.2') + at('1.3') + at('1.4')");
  17. t.end();
  18. })
  19. test('string test2', function(t){
  20. var str="hello(world)";
  21. var nstr = str.replace(/\([^\)]*\)/g,"");
  22. t.equal(nstr , "hello");
  23. t.end();
  24. })
  25. test('string test3', function(t){
  26. var str="共 (%S) 页";
  27. var nstr = str.replace("(%S)",10);
  28. t.equal(nstr , "共 10 页");
  29. t.end();
  30. })
  31. test('test extract', function(t){
  32. let private_extract_code = function(str, idx){
  33. let rst = '', lBracket = 0, rBracket = 0, firstIdx = idx, lastIdx = 0;
  34. for (let i = idx; i < str.length; i++) {
  35. if (str[i] === '(') {
  36. lBracket++;
  37. if (lBracket == 1) firstIdx = i + 1;
  38. }
  39. if (str[i] === ')') {
  40. rBracket++;
  41. if (lBracket == rBracket) {
  42. lastIdx = i - 1;
  43. if (lastIdx > firstIdx) {
  44. if (str[firstIdx] === "'") firstIdx++;
  45. if (str[lastIdx] !== "'") lastIdx++;
  46. if (lastIdx > firstIdx) {
  47. rst = str.slice(firstIdx, lastIdx);
  48. }
  49. }
  50. break;
  51. }
  52. }
  53. }
  54. return rst;
  55. };
  56. let code = private_extract_code("at('1.1') + at('1.2')", 10);
  57. t.equal(code , "1.2");
  58. t.end();
  59. })