0

I am trying to write a Javascript function which takes a 1, 2 or 3 word phrase and returns the same phrase, but the first found space is replaced with a <br>

so

Hello My World

becomes

Hello<br>My World

or

Hello World

becomes

Hello<br>World.

Ideas?

3 Answers 3

2
function space2br(str, limit){
    for(var i = 0; i < limit; i++)
        str = str.replace(/\s/, '<br>');
    return str;
}

space2br('Hello My World', 1); // "Hello<br>My World"
space2br('Hello My World', 2); // "Hello<br>My<br>World"

function firstSpace2br(str){
    return space2br(str, 1);
}

firstSpace2br('Hello My Favourite World'); // "Hello<br>My Favourite World"
Sign up to request clarification or add additional context in comments.

Comments

1

You could equally change this to a set of options, but passing blanks works fine too for optional ordered params:

http://jsfiddle.net/MHRbF/

<div id='test'></div>
<div id='test2'></div>
<div id='test3'></div>

Then in js:

function replaceMe(sString, sTarget, sWith, nCount){
    if(!sString) return 'Please provide a string';
    if(!sTarget) sTarget = /\s/;
    if(!sWith) sWith= '<br/>';
    if(!nCount) nCount = 1;
    for(var c = 0; c < nCount; c++)  sString= sString.replace(sTarget, sWith);
    return sString;
}

x = 'Hello Crazy World Full of People!';
y = replaceMe(x);
document.getElementById('test').innerHTML = y;
y = replaceMe(x,'','',10);
document.getElementById('test2').innerHTML = y;
y = replaceMe(x,'','',2);
document.getElementById('test3').innerHTML = y;

You get the idea how this becomes pretty flexible.

Comments

1

Try a simple regex replace

'Hello My World'.replace(/\s/, '<br />')

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.