如何通过使用javascript

时间:2015-06-05 10:02:58

标签: javascript html5

Anion Gap
Body Surface Area (BSA)
Creatinine Clearance
Stack Overflow

我想在Text之前添加“String”,在文本结束之后添加“String”。

我有以下表达式,它在excel中完美运行: -

= CONCATENATE( “”,B1, “”)

输出: -

<string>Anion Gap</string>
<string>Body Surface Area (BSA)</string>
<string>Creatinine Clearance</string>
<string>Stack Overflow</string>

从上面,任何人都可以帮助我。我想要用户界面代码(html格式),它应该从用户或textarea框接受excel文件,用户可以在其中放置他的文本,然后应用此代码和如输出中所示生成它。

1 个答案:

答案 0 :(得分:1)

行。这里有一些JavaScript代码可以生成您需要的输出:

pad是一个递归函数,可生成任何所需的尾随零。

function pad(num, diff) {
    return diff > 0 ? pad(num, diff - 1) + 0 : num;
}

processString完成大部分工作。请注意,此代码仅适用于您的问题的单位数字。例如,它不能正确地在1.12.1上工作。

function processString(num) {

    // remove any existing dots
    var tmp = num.replace(/\.+/g, '');

    // calculate the difference between the desired length of the string
    // and the current string
    var diff = 4 - tmp.length;

    // generate a template
    var tmpl = '<string>#{padded}</string>';

    // if the diff is greater than zero return the padded string
    // with the dots added back in otherwise return the original string
    var padded = diff > 0 ? pad(tmp, diff).split('').join('.') : num;
    return tmpl.replace('#{padded}', padded);
}

然后,当然,您需要将textarea添加到您的页面:

<textarea id="area"></textarea>
<button id="submit">Submit</button>

还有一些额外的JavaScript来抓取添加的文本并将其转换为:

function processArea() {
    var area = document.getElementById('area');

    // split the text at each carriage return
    var arr = area.value.split(/\n/);

    // loop over each string and process it
    for (var i = 0, l = arr.length; i < l; i++) {
      arr[i] = processString(arr[i]);
    }

    // repopulate the text area with the output
    area.value = arr.join('\r\n');
}

DEMO

另一方面,如果您需要考虑多位数字,请将以上两个函数替换为:

function pad(num) {
    if (num.length < 4) {
      num.push('0');
      pad(num);
    }
    return num;
}

function processString(num) {
    var tmp = num.split('.');
    var diff = 4 - tmp.length;
    var tmpl = '<string>#{padded}</string>';
    var padded = diff > 0 ? pad(tmp).join('.') : num;
    return tmpl.replace('#{padded}', padded);
}

DEMO