【问题标题】:Return value of string字符串的返回值
【发布时间】:2017-01-03 14:15:44
【问题描述】:

我有字符串 format,其中包含数字 {0}、{1}、{2}。我希望这些数字被输入类型placeholder = "Outside,beautiful,blue" 中的占位符写入的单词替换,即format[i+1] 的值等于字符串words 的索引(包含占位符中的单词)。结果在控制台中得到这样的东西:

外面是如此美丽,蓝天,美丽的大自然和蓝色太平洋旁边的房子......

HTML:

<!Doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta name="viewport" content="width=device-width">
        <meta charset="utf-8">
        <title>Exercises in JS</title>
        <script src="exercises.js"></script>
    <body>
        <label for="myText">Input array:</label>
            <input type="text" name="wordcount" id="myText" placeholder = "Outside,beautiful,blue" value="" />
        <a href="#" id="sub">Submit</a>
    </body>
    </head>
</html>

Javacript 代码:

window.onload = function(){

inputBox = document.getElementById("myText");
btn = document.getElementById('sub');   

btn.addEventListener("click",function(event){
event.preventDefault();
    stringFormat(inputBox.value);   
});

    str = inputBox.value;
    var format = '{0} is so {1} with {2} sky, {1} nature and house next to the {2} pacific ocean...';

    function stringFormat(str) {
        var words = document.getElementById("myText").placeholder.split(",");

        for (var i = 0; i < format.length; i++) {
            if (format[i] === '{' && format[i+1] == '0') {
                format = format.replace(format[i+1], words[i]);        
            }

            else if (format[i] === '{' && format[i+1] > '0') {
                format = format.replace(format[i+1], words['$[i]']);
            }
        }
        console.log(format);       
    }
} 

【问题讨论】:

  • 不要遍历输入字符串,而是遍历 words 数组,每个循环只替换 "{" + i + "}"

标签: javascript string methods


【解决方案1】:

听起来像是正则表达式的工作:

str = "{0} is so {1} with {2} sky, {1} nature and house next to the {2} pacific ocean..."

words = 'Outside,beautiful,blue'.split(',')

result = str.replace(/{(\d+)}/g, m => words[m[1]]);

console.log(result)

没有正则表达式,它也将是一个单行:

str = "{0} is so {1} with {2} sky, {1} nature and house next to the {2} pacific ocean..."

words = 'Outside,beautiful,blue'.split(',')

result = words.reduce((str, word, n) => str.split('{' + n + '}').join(word), str);

console.log(result)

【讨论】:

    【解决方案2】:

    有两种方法可以做到这一点:

    1. 遍历字符串中的占位符,检索等效单词。使用String#replace 的回调函数和正则表达式真的很容易做到这一点。

    2. 遍历单词并使用单独的操作将"{" + indexOfWord + "}"替换为相关单词。

    我会使用 #1,它看起来像这样:

    function stringFormat(str, words) {
        return str.replace(/\{(\d+)\}/g, function(m, c0) {
            return words[c0] || "";
        });
    }
    

    详情:

    • 正则表达式/\{(\d+)}/ 查找模式{n},其中n 是一个数字,并在捕获组中捕获n
    • replace 调用它的回调函数,参数是它找到的整体匹配(例如,"{0}"),后跟任何捕获组的值。由于我们在数字周围有一个捕获组,所以我们得到的第二个参数就是这些数字,例如"0"
    • 我们使用它来索引words 的数组(请记住,数组索引不是真正的数字,因为数组aren't really arrays,我们使用字符串很好)来查找等效词。李>
    • 如果有一个占位符没有匹配的单词,如果words[c0]undefined,我们使用curiously-powerful || operator 来获取""
    • 我们返回希望用于每次替换的字符串,replace 为我们放入结果字符串。

    (以上两个链接都指向我贫血的小博客。)

    例子:

    function stringFormat(str, words) {
      return str.replace(/\{(\d+)\}/g, function(m, c0) {
        return words[c0] || "";
      });
    }
    
    console.log(
      stringFormat(
        "{0} is so {1} with {2} sky, {1} nature and house next to the {2} pacific ocean...",
        "Outside,beautiful,blue".split(",")
      )
    );

    但如果你更喜欢#2,那也是完全可行的;您仍然必须使用正则表达式来替换所有占位符:

    function stringFormat(str, words) {
        words.forEach(function(word, index) {
            // (Have to escape `{` because it's a quantifier)
            str = str.replace(new RegExp("\\{" + index + "}", "g"), word);
        });
        return str;
    }
    

    在该示例中,我们必须转义 {,因为它在正则表达式中具有特殊含义。 (我们也可以转义},但我们不必这样做;它只有在与未转义的{ 配对时才具有特殊含义。)

    例子:

    function stringFormat(str, words) {
      words.forEach(function(word, index) {
        // (Have to escape `{` because it's a quantifier)
        str = str.replace(new RegExp("\\{" + index + "}", "g"), word);
      });
      return str;
    }
    
    console.log(
      stringFormat(
        "{0} is so {1} with {2} sky, {1} nature and house next to the {2} pacific ocean...",
        "Outside,beautiful,blue".split(",")
      )
    );

    但是你会想要转义 word 中任何在正则表达式中特殊的字符,如果有的话(我没有在上面打扰),并且它需要多次通过细绳。所以总的来说,#1。

    【讨论】:

    • 感谢您的帮助!但我没有得到你使用的所有东西 - 我们只转义 '{' 但我们不转义 '}' 以及他如何知道哪个是索引并取回正确的单词?
    • @Santiya:对不起,我已经加强了上面的解释。
    • 非常感谢您最深入的解释!问候!
    猜你喜欢
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    • 2016-08-26
    • 1970-01-01
    相关资源
    最近更新 更多