My shortcode function work with or without square brackets. But i want, it only work with square brackets.
shortcode (I don’t want)
itemText num="1" title="This is a title"
shortcode (I want)
[itemText num="1" title="This is a title"]
Here is my code
function shortCode(a, b, c) {
var split = a.split(" "),
regex = /(?<=")w.*?(?=")/g;
for (var i = 0; i < split.length; i++) {
var pair = split[i].split("=");
if (pair[0].trim() == b) {
c = pair[1];
if (c.match(regex) != null) {
return String(c.match(regex)).trim()
} else {
return false
}
}
}
return false
}
Example
function shortCode(a, b, c) {
var split = a.split(" "),
regex = /(?<=")w.*?(?=")/g;
for (var i = 0; i < split.length; i++) {
var pair = split[i].split("=");
if (pair[0].trim() == b) {
c = pair[1];
if (c.match(regex) != null) {
return String(c.match(regex)).trim()
} else {
return false
}
}
}
return false
}
$(".test span").each(function () {
var $this = $(this),
text = $this.html(),
mtc = text.toLowerCase(),
num = shortCode(text, "num"),
title = shortCode(text, "title");
if (mtc.match("itemtext")) {
$this.text(num + " " + title); //expected output: 1 This is a title
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test">
<span>itemText num="1" title="This is a title"</span>
</div>
2
Answers
I’d suggest using a modern framework such as React, or even AngularJS will do for your case.
Alternatively, I’d suggest using mature templating solutions, like Mustache.
Or to put all the data like so:
<span data-title="my title" />
, etc.It’ll be a nightmare to invent and maintain your custom solution, a lot of regular expressions to parse, to consider edge cases, like spaces or special characters in titles, etc.
But it’s holidays time, so here’s a code that you asked for:
Here is a shorted code that changes the span only if its content is enclosed in square brackets. The code of the
shortCode()
function is also shortened.Explanation of the regex in
shortCode()
:\b
— word boundary to avoid false positives for attributes+ attr +
— attribute="
— literal="
text([^"]*)
— capture group 1: everything up to and excluding"
Explanation of
^[itemtext .*]$
regex:^
— anchor at start of string[
— expect[
itemtext
— literal text (includes trailing space).*
— greedy scan]
— expect]
$
— anchor at end of string