简体   繁体   中英

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. 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.

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?)

Thanks a lot T

Build a filter that implements the logic of the transformation JS string with bracket tags -> HTML string with normal tags.

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:

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 ). 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.

Use regex

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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