0

I have a simple loop to delete all words from the end of a text that start with a # and space. AS3:

//   messageText is usually taken from a users input field - therefore the newline is not present in the "messageText"

var messageText = "hello world #foo lorem ipsum #findme"
while (messageText.lastIndexOf(" ") == messageText.lastIndexOf(" #")){
messageText = messageText.slice(0,messageText.lastIndexOf(" "));
}

How to check if the position before the # is not a space but a newline? I tried this but nothing gets found:

while (messageText.lastIndexOf(" ") == messageText.lastIndexOf("\n#")){
messageText = messageText.slice(0,messageText.lastIndexOf(" "));
}
Matt
  • 2,981
  • 5
  • 23
  • 33
  • overly complicated piece of code when a simple String.split('#')[0] will get you close to the wanted result. – BotMaster May 13 '15 at 18:41
  • That would not work if a link like this is in the string or am I wrong?: `http://example.com/#contact` – Matt May 13 '15 at 19:44

1 Answers1

1
\n is the newline character in the Unix file definition.
\r\n is the Windows version.
\r is the OSX version.

See also: this previous (dupe) post.

First thing is I'd manually try replacing "\n" with "\r\n" and then "\r" to see if there is some other newline in use. If so, then you just need a better search term that will match each version in one go.

A better solution might be to use Regular Expression (RegExp). You are explicitly looking for the newline character and a space after it. You could use this regex pattern to look for the start of a line with a single space:

var pattern:RegExp = /^\s/; 
if (yourString.search(pattern) >= 0) { ... }

The ^ carat character enforces that it's the start of a line. The \s is a placeholder for any whitespace character, so if you don't want to match tabs then change it to a blank space. (I'm not familiar with ActionScript specifically, but that syntax looks OK and search() will return -1 if the pattern isn't found).

Community
  • 1
  • 1
msenne
  • 613
  • 5
  • 8