Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
rolandlearns
4,223 PointsI want to program a text transformer. where to start?
I don't have much jquery or javascript knowledge yet, but need to build a sort of text transformer. basically I want to paste a block of text into a form and then some parts of it automatically get changed, for example if there is a html link to an image (example: src="http://www.textserver.com/asbsdf/testimage.jpg", the domain automatically gets deleted and changed to src="../testimage.jpg" or the word red get's changed to green.
how hard is this to do? where best to start to just achieve this?
2 Answers
Michael Liendo
15,326 PointsOne way would be to take the block a text (essentially one long string), and use JavaScript's indexOf() method to find out the index of where you want to begin, the nice thing about his method is that it takes an optional second parameter as a starting point. Then combine that with JavaScript's slice() method.
An example outline without jQuery would be: 1) store the text block in a variable ie. var textBlock = "someStuff_http://yourLink.jpg_moreStuff"; 2) get the index of the link if the link exists: var startIndex = textBlock.indexOf("http://"); 3) get the end of your link: var endInext = textBlock.indexOf("jpg", startIndex); //index returned is the index of "j" //now you know where the link starts and ends 4)take out the link: var link = textBlock.slice(startIndex, endIndex + 2); //added 2 to get the "p" and "g" in "jpg"; 5) replace the text: textBlock.replace(link, yourNewLinkString);
It's tricky with links, because I'm assuming you won't know their domain routes ahead of time, if so, just skip to step 5 and call replace(). You would also just skip to replace in the case of your changing color example.
Lastly, it should be noted that the outline above, will only find the first link and change it. If you wanted to create function that looked through all, it would be more or less the same, but you'd want to capture the index of where you left off and start from there.
rolandlearns
4,223 PointsThanks Michael,
I'll get on it and report back how it went.