Skip to content Skip to sidebar Skip to footer

Find And Alter Text In A String Based On Ln # And Character #

How can I prepend characters to a word located at a particular Ln # and character # in text? Example: The use case is when a person enters code into a textarea (like jsFiddle), I f

Solution 1:

You can save the lines of the textarea into an array:

var lines = $('#textarea').val().split(/\n/);

And from there you take the substring of a particular line and assign it to your object:

MyObj.first_name.value = lines[0].substring(29,39)

Hope that helps!

Solution 2:

If you're just trying to replace first_name and last_name the simplest solution would be to use replace(), for example:

usersCode.replace("first_name", MyObj.first_name.value);
usersCode.replace("last_name", MyObj.last_name.value);

If you're insistent on doing the line number and character number specific thing, we can arrange that, but it's not at all necessary for what it seems like you're asking for. Perhaps I'm mistaken, though.

Update:

Okay so you want to replace all instances? Finding line numbers and all that is still unnecessary, just use this:

usersCode.replace(/first_name/g, MyObj.first_name.value);
usersCode.replace(/last_name/g, MyObj.last_name.value);

g is a RegEx flag for global searching.

Update 2:

usersCode.split("\n")[lineNumber - 1].replace(usersCode.split("\n")[lineNumber - 1].substr(29, 39), MyObj.first_name.value);

You can replace 29 and 39 with variables startChar and endChar respectively. lineNumber will also need to be provided by you.

Solution 3:

RegEx can easily search based on characters but not via position. Though you can still do it using regEx but the soultion will become more and more complex. For this case you don;t need a pure RegEx answer. Code below is what you need.

k=$('#regex_string').val()

functionfindAndReplaceWord(lineNo, startPos, endPos, replaceWith) {
    var line = k.split(/\n/)[lineNo];
    if(line) {
        var word = line.substring(startPos, endPos)

        return k.replace(word, replaceWith)
    }
}

findAndReplaceWord(0, 29, 39, MyObj.first_name.value)

Post a Comment for "Find And Alter Text In A String Based On Ln # And Character #"