简体   繁体   English

检测字符串中的“模式”,并将其<sup>标签</sup>包装<sup>在javascript(角度)中</sup>

[英]Detect “pattern” in a string and wrap it <sup> tags in javascript(angular)

So basically what i want to achieve is the following: 所以基本上我想要实现的是以下内容:

All the text on the page is being fed from JSON files. 页面上的所有文本均由JSON文件提供。 I have a service that parses and prints it to the document with no problem. 我有一项服务,可以毫无问题地将其解析并打印到文档中。 My issue now is that when this text is written to json, i have limited control over it and i need to detect anything within square brackets [Like This 2011] and wrap it in tags. 现在的问题是,当将此文本写入json时,我对此的控制有限,我需要检测方括号中的任何内容(例如“ This This 2011”),并将其包装在标签中。

I'd appreciate if someone could help me with this in js and possibly advice on what might be the best way to implement that in angularjs world.. (do it on the controller? service? in the view itself?) 如果有人可以在js中为我提供帮助,并且可能对在angularjs世界中实现该方法的最佳方式提出建议,我将不胜感激。(在控制器本身还是服务中?在视图本身中?)

Thanks a lot T 非常感谢T

Build a filter that implements the logic of the transformation JS string with bracket tags -> HTML string with normal tags. 构建一个过滤器,该过滤器使用方括号标签->具有常规标签的HTML字符串实现转换JS字符串的逻辑。

Writing a filter is easy. 编写过滤器很容易。 The logic inside it could be more complex, depending on what you need. 其中的逻辑可能会更复杂,具体取决于您的需求。 Having written the filter (lets name it bracketXformer ), its usage would be: 编写了过滤器(将其命名为bracketXformer )后,其用法将是:

Model example: 型号示例:

$scope.pageContent = {
    title: "The Title",
    content: "Bla bla [bla]"
};

Template example: 模板示例:

<h2>{{ pageContent.title }}</h2>
<p>{{ pageContent.content | bracketXformer }}</p>

Also search for Markdown implementations in Javascript (eg Showdown ). 还搜索Java中的Markdown实现(例如Showdown )。 Could save you some time implementing the filter, if it matches your use case. 如果它与您的用例相匹配,则可以节省您实施过滤器的时间。 If Markdown suits you, also look here for an approach using Angular directives. 如果Markdown适合您,请在此处查找使用Angular指令的方法。

Use regex 使用正则表达式

var text = 'some text [sup stuff] here';

document.write(text.replace(/\[(.*)\]/g, '<sup>$1</sup>'));

jsfiddle: http://jsfiddle.net/uH9x2/ jsfiddle: http : //jsfiddle.net/uH9x2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM