2

I am trying to replace multiple delimiters within a single string with a break tag, but the delimiters are not always the exact same or of the same length. The delimiters do follow this pattern when within the string: #[some number];#

For example, I want

49;#Simpson, Homer;#45;#Simpson, Bart

to become

Simpson, Homer
Simpson, Bart

And I want

49;#Simpson, Homer;#45;#Simpson, Bart;#101;#Simpson, Lisa

to become

Simpson, Homer
Simpson, Bart
Simpson, Lisa

I was using the following to remove the first [number];# from the string, but I'm not sure how to replace the rest.

peopleString = peopleString.substring(peopleString.indexOf(";#") + 2);

Thanks!

2
  • Do the numbers mean anything or...? Commented May 6, 2015 at 12:28
  • The numbers are the ID of the person, but I don't care about them for this example. They can be be any number of digits 1, 2, 3, etc. Commented May 6, 2015 at 12:37

3 Answers 3

2

Here's a solution that uses regex after your initial replacement of the first [number];#,

Some more info about regular expressions: https://stackoverflow.com/tags/regex/info

var replacement = '<br>';
var doReplace = function(str) {
  str = str.substring(str.indexOf(";#") + 2);
  return str.replace(/;#[0-9]+;#/g, replacement);
}

document.write(doReplace('49;#Simpson, Homer;#45;#Simpson, Bart'));
document.write('<br>---<br>')
document.write(doReplace('49;#Simpson, Homer;#45;#Simpson, Bart;#101;#Simpson, Lisa'));

Sign up to request clarification or add additional context in comments.

Comments

0

This is an excellent candidate for the Regular Expression replace function:

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

Look into using the replace function and the Global flag to replace all instances of your delimiter

Comments

0

You could use Regular Expressions to do that.

you could try with sample

var string = '49;#Simpson, Homer;#45;#Simpson, Bart;#101;#Simpson, Lisa'
string.replace('/;*#*\d+;#*/g','');
console.log('result',string);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.