简体   繁体   中英

JavaScript substr(), Get Characters in the Middle of the String

I have a string, var str = "Runner, The (1999)";

Using substr(), I need to see if ", The" is contained in str starting from 7 characters back, then if it is, remove those characters and put them in the start. Something like this:

if (str.substr(-7) === ', The') // If str has ', The' starting from 7 characters back...
{
    str = 'The ' + str.substr(-7, 5); // Add 'The ' to the start of str and remove it from middle.
}

The resulting str should equal "The Runner (1999)"

Please, no regular expressions or other functions. I'm trying to learn how to use substr.

var str = "Runner, The (1999)";
if(str.indexOf(", The") != -1) {
    str = "The "+str.replace(", The","");
}

Here you go, using only substr as requested:

var str = "Runner, The (1999)";

if(str.substr(-12, 5) === ', The') {
    str = 'The ' + str.substr(0, str.length - 12) + str.substr(-7);
}

alert(str);

Working JSFiddle

It should be noted that this is not the best way to achieve what you want (especially using hardcoded values like -7 – almost never as good as using things like lastIndexOf , regex, etc). But you wanted substr , so there it is.

If you want to use just substr:

var a = "Runner, The (1999)"
var newStr;
if (str.substr(-7) === ', The')
    newStr= 'The ' +a.substr(0,a.length-a.indexOf('The')-4) + a.substr(a.indexOf('The')+3)

Use a.substr(0,a.length-a.indexOf('The')-4) to obtain the words before "The" and a.substr(a.indexOf('The')+3) to obtain the words after it.

So, you say that the solution should be limited to only substr method. There will be different solutions depending on what you mean by:

", The" is contained in str starting from 7 characters back

If you mean that it's found exactly in -7 position, then the code could look like this (I replaced -7 with -12, so that the code returned true):

function one() {
  var a = "Runner, The (1999)";
  var b = ", The";
  var c = a.substr(-12, b.length);
  if (c == b) {
    a = "The " + a.substr(0, a.length - 12) +
    a.substr(a.length - 12 + b.length);
  }
}

If, however, substring ", The" can be found anywhere between position -7 and the end of the string, and you really need to use only substr, then check this out:

function two() {
  var a = "Runner, The (1999)";
  var b = ", The";
  for (var i = a.length - 12; i < a.length - b.length; i++) {
    if (a.substr(i, b.length) == b) {
      a = "The " + a.substr(0, i) + a.substr(i + b.length);
      break;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM