在字符串变量(javascript)中的字符前插入几个字符

时间:2016-08-08 19:00:38

标签: javascript arrays string

我有以下javascript变量。

var data = "ashley, andy, juana"

我希望以上数据看起来像这样。

var data = "Sports_ashley, Sports_andy, Sports_juana"

它应该是动态的。此变量中可以包含任意数量的逗号。

有人可以让我轻松地实现这一目标。

3 个答案:

答案 0 :(得分:2)

使用 var correct:Int = 0 func qa(question: String, answer: String) { show(question) var ans = ask("answer") if (ans.lowercased() == answer) { show("correct") correct = correct + 1 } else { show("wrong you numpty!") } } func qaor(question: String, answer: String, answer2: String) { show(question) var ans = ask("answer") if (ans.lowercased() == answer) || (ans.lowercased() == answer2) { show("correct") correct = correct + 1 } else { show("wrong you numpty!") } } show("What is your name?") let name = ask("Name") show("Hi " + name) qa(question: "What is the name of the character played by Simon Jones in the Hitchikers Guide to the Galaxy?", answer: "arthur dent") qaor(question: "What is voiced by Peter Jones in the Hitchikers Guide to the Galaxy?", answer: "the book", answer2: "the guide") qa(question: "finish this sentence .doing the coastlines was always my Favourite, the rough crinkley edges, .... ", answer: "fjords") var cf = "no" if (correct == 0) { var cf = "no" } else if (correct == 1) { var cf = "one" } else if (correct == 2) { var cf = "two" } else if (correct == 3) { var cf = "three" } show("you got " + cf + " questions correct out of three") 应该可以在每个逗号之前添加运动。下面我列举了一个例子。

.replace

在该示例中,使用带有g标志的RegExp将使用var data = data.replace(/,/g , ", Sports_"); 替换所有逗号,而不仅仅是第一次出现。

然后在结束时你应该能够将Sports,追加到最后。

Sports

答案 1 :(得分:2)

可能是一种矫枉过正,但这是一个通用的解决方案

function sportify(data) {
  return data
    .split(/\s*,\s*/g) //splits the string on any coma and also takes out the surrounding spaces
    .map(function(name) { return "Sports_" + name } ) //each name chunk gets "Sport_" prepended to the end
    .join(", "); //combine them back together
  }

console.log(sportify("ashley, andy, juana"));
console.log(sportify("ashley   , andy,     juana"));

String.replace()

Array.map()

Array.join()

编辑:使用新版本的OP更新

答案 2 :(得分:2)

使用正则表达式使用String#replace()替换所有出现的 cloning Repo Cloning into '/repo'... changing directory 或字符串的开头



,