【问题标题】:Javascript - Insert string into text at variable locationsJavascript - 在可变位置将字符串插入文本
【发布时间】:2017-05-16 22:53:47
【问题描述】:

我有一个存储在数据库中的大文本字段。文本字段在特定位置以变量为种子,类似于 console.log() 的工作方式。

“此文本由 $user1 在 $date 撰写,而 $user1 正在与 $user2 一起完成 $subject”

然后我可以用正确的动态值替换变量。

很好奇是否有一种直接的方法来解决这个问题,或者我是否被困在每个位置拆分字符串然后使用新值重建。

【问题讨论】:

  • 你的变量是什么样的?提供您使用的完整字符串/变量/数据。

标签: javascript string text replace


【解决方案1】:

String.prototype.replace 可以使用RegExp 进行匹配和动态确定替换字符串的函数调用。如果您可以创建一个对象映射,其属性名称与格式字符串中的变量相同,并且值与替换本身相同,则可以通过使用匹配的属性名称从映射对象中获取相应的值,一次性全部替换它们.

类似这样的:

var format = "This text was written by $user1, on $date, while $user1 was working with $user2 to complete the $subject";

var replacementsMap = {
    user1: "John",
    date: new Date(),
    user2: "Jane",
    subject: "Collaboration Project"
};

var result = format.replace(/\$([a-z]+\d*)/g, function(match, prop) {
    // match => the full string matched by the regex (e.g. $user1, etc)
    // prop => the captured part of the match (i.e. not including the $)
    return replacementsMap[prop];
});

document.getElementById("result").innerHTML = result;
<div id="result"></div>

【讨论】:

  • 天才!谢谢布赖恩
【解决方案2】:

你可以在javascript中使用replace函数,它使用正则表达式。

例子:

var user1 = "Joe";
var original = "This text was written by $user1, on $date, while $user1 was working with $user2 to complete the $subject";
var newString = original.replace(/\$user1/g, user1);

等等。

【讨论】:

  • 不客气 :) 如果有帮助,请将其标记为答案
猜你喜欢
  • 2016-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多