I want to insert \n
in the second space in a string, so for example if a string has more than 1 space, it means I can add \n
in the second space, if not, it means it is just one word or a string with one space and I would like to have and else
where I can print it normal, so in this example, I have Hi I am here testing
string, then I would like to raplace the second space with \n
then it would be Hi I\nam here testing
so in console it would print that string in the next way:
Hi I
am here testing
I was trying to do this with replace(/ /g,"\n")
but it replaces all spaces.
I hope someone could help me, thanks.
CodePudding user response:
One possibility would be to use a regex to match from start of string up to the second group of spaces (1 or more) and replace that set of spaces with a newline:
const str = 'Hi I am here testing'
const regex = /^(\S \s \S )\s /
const result = str.replace(regex, '$1\n')
console.log(result)
Another possibility is to split the string on spaces and then join it back together with a newline replacing the space between the second and third word:
const str = 'Hi I am here testing'
const parts = str.split(/(\s )/)
const result = parts.slice(0, 3).join('') '\n' parts.slice(4).join('')
console.log(result)
CodePudding user response:
A simple solution:
function breakLineOnSecondSpace(sentence) {
const SPACE = ' ';
var spaceCount = 0;
var secondSpaceIndex = -1;
for (var i = 0; i < sentence.length; i ) {
var char = sentence[i];
if (char == SPACE) spaceCount ;
if (spaceCount === 2) {
secondSpaceIndex = i;
break;
}
}
if (secondSpaceIndex > -1) {
return [
sentence.substring(0, secondSpaceIndex),
sentence.substring(secondSpaceIndex 1, sentence.length),
].join('\n');
} else {
return sentence;
}
}
console.log(breakLineOnSecondSpace('Hi I am here testing'));
Working example: Stackblitz
CodePudding user response:
you can do it with foreach in an easy way
var myname = "alex is software engineer";
myname = myname.split("");
var actualString = "";
var spaceCounter = 0;
myname.forEach(element => {
if(element != " ")
{
actualString = element;
}
else
{
spaceCounter ;
if(spaceCounter == 2)
{
actualString ="\n";
return;
}
else
{
actualString = " ";
}
}
});
console.log(actualString);