You could do this (just an outlined idea, no code):
Devise a regex that matches your entire text. Use fixed strings for the unmodifiable parts, and use [sS]*?
for the modifiable parts. Use ^
and $
to anchor your regex.
/^This is fixed text. Now something editable:[sS]*?Now fixed again.$/
Now react to the keyup
event, and probably other events as well (like paste
).
With every relevant event, make a check if the regex still matches.
If it doesn't, cancel the event.
Effectively, this should stop modifications to parts that are literal in the regex and thus make certain parts of your text read-only.
Don't forget to test the string on the server side as well after the form post - never trust that the client cannot send invalid values.
EDIT
You can use a regex quote function to dynamically build that regex from strings, this should save you a lot of the hassle.
function regexQuote(s) { return s.replace(/[[]^$*+?{}.|\]/g, "\$&") }
usage
var re = new Regex(
"^" +
[regexQuote(fixedPart1), regexQuote(fixedPart2)].join("[\s\S].*?")
+ "$"
);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…