【问题标题】:How to find a particular value in a string in js如何在js中查找字符串中的特定值
【发布时间】:2017-08-11 10:54:12
【问题描述】:

我有这样的数据,

   var str = "#data time #city";

我的目标是把它变成

 var str = <a src="www.test/data">#data</a> time <a src="www.test/city">city</a>

我的意思是在我找到的字符串中 # 它的下一个值,即数据应该设置为链接 www.test/{{param}} 的参数,并且应该用链接包围。任何人都可以建议帮助。谢谢。

【问题讨论】:

  • 字符串替换不会改变原始字符串。
  • 考虑使用正则表达式?

标签: javascript html angularjs arrays string


【解决方案1】:

对于这种情况,String.replace() function 将为您提供帮助:

var str = "#data time #city"
str = str.replace(/#(\S+)/g, '<a href="#$1">#$1</a>')
output.textContent = str
clickable.innerHTML = str
#output { font-family: courier }
<div id="output"></div>
<div id="clickable"></div>

【讨论】:

  • 感谢 b4xter,但我希望这些锚标签可点击。
  • 我将生成的 HTML 插入到 DIV 中,以便您看到它的“可点击”。
【解决方案2】:

以下代码将您的数据转换为预期的输出。 document.write(..) 用于调试。

var data='#data time #city';
var hashtags = data.match(/#\S+/g);   

document.write('before: ' + data + '</br>');

for (j = 0; j < hashtags.length; j++) {
    // remove # from hashtag
    var tag = hashtags[j].substring(1, hashtags[j].length); 
    // create the link
    var link = '< a src="www.test/' + tag + '>#' + tag + '< / a > ';
    
    // replace hashtag with link 
    data=data.replace(hashtags[j], link);
}

document.write('after: ' + data);

【讨论】:

  • 我已经从您的代码中维护了初始结构,但 b4xter 的答案更优雅,如果可能,您应该使用那个。
猜你喜欢
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多