2

I have a string like that:

I'm a string not too long but neither so short

Let's take the word 'not' inside the string: it starts at position number 13 and it ends at position numer 16.

There's a way with JQuery to substitute the word between position 13 and position 16 with this:

<b>not</b>

I know only the position of the string that i want to replace not it's content.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
Matteo Pagliazzi
  • 5,140
  • 12
  • 49
  • 83
  • Try having a look at this [Replacing at particular index][1] [1]: http://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript – Matthew Riches Jun 06 '12 at 14:01
  • This should not require any jQuery. A few plain JavaScript string functions and you're good. I know what you mean, though - I always look to jQuery first, but sometimes plain JavaScript will do it without any fuss. – Surreal Dreams Jun 06 '12 at 14:05

3 Answers3

4

You can mostly use good old-fashioned JavaScript to do this, but you can use jQuery for the DOM manipulation (though you don't have to).

http://jsfiddle.net/hQUhX/

contents:

function replacePiece(str, start, end) {
   var component = str.substr(start, end - start);
   var newstr = str.substr(0,13) + "<b>" + component + "</b>"
      + str.substr(end);
   return newstr;
}

​$("#Str").html(replacePiece($("#Str").text(), 13, 16));
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • If you don't even know the starting position, but know the word, you can use `indexOf` method to get the index of that word.. something like [this JSFiddle](http://jsfiddle.net/hQUhX/28/) – sohaiby May 25 '15 at 13:22
1

This answer is for replacing when you ONLY know the STARTING position

What I ended up doing is answering based on only knowing the starting position, not the end position of the word.

What this does is grab the string from the known starting position, split it by spaces, then wrap the first word with <b>, then adds that back in between the string and outputs that.

JSFiddle Example http://jsfiddle.net/Jc829/4/

Sorry for not paying more attention the first time around.

Also, you don't really need jQuery for this.

Josh Allen
  • 987
  • 12
  • 30
0

While I've accepted Explosion Pills answer I think this is a more polished way to do this (thanks to Matthew Riches for the link)

String.prototype.replacePiece = function(replace_with, start, end) {
    return this.substring(0, start) + replace_with + this.substring(end, this.length)
}

var str = "Helloiworld";

var replace_with = "<b>i</b>";

alert(str.replacePiece(replace_with, 5, 6));​​

http://jsfiddle.net/paglia_s/QTMJG/

Matteo Pagliazzi
  • 5,140
  • 12
  • 49
  • 83