admin管理员组文章数量:1134247
I have a string: "The quick brown fox jumps over the lazy dogs."
I want to use JavaScript (possibly with jQuery) to insert a character every n characters. For example I want to call:
var s = "The quick brown fox jumps over the lazy dogs.";
var new_s = UpdateString("$",5);
// new_s should equal "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs.$"
The goal is to use this function to insert ­ into long strings to allow them to wrap.
Maybe someone knows of a better way?
I have a string: "The quick brown fox jumps over the lazy dogs."
I want to use JavaScript (possibly with jQuery) to insert a character every n characters. For example I want to call:
var s = "The quick brown fox jumps over the lazy dogs.";
var new_s = UpdateString("$",5);
// new_s should equal "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs.$"
The goal is to use this function to insert ­ into long strings to allow them to wrap.
Maybe someone knows of a better way?
Share Improve this question edited Jul 18, 2020 at 1:55 someone 3581 silver badge14 bronze badges asked Nov 20, 2009 at 20:07 brendanbrendan 30k20 gold badges69 silver badges109 bronze badges 4- You're better off letting the browser wrap text. Do you have long sentences like you used for your example above, or long words? – Dan Herbert Commented Nov 20, 2009 at 20:10
- 1 The browser won't wrap within a word, I have long words like "ThisIsAStupidLabelThatOneOfMyUsersWillTryToMakeInMyApplication" – brendan Commented Nov 20, 2009 at 20:15
- Wouldn't a server side solution to break words into a maximum of n characters would be better? – Pool Commented Nov 20, 2009 at 20:19
- Possibly, but a client side solution is more easily implemented for my current predicament. – brendan Commented Nov 20, 2009 at 20:26
9 Answers
Reset to default 224With regex
"The quick brown fox jumps over the lazy dogs.".replace(/(.{5})/g,"$1$")
The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs.$
function chunk(str, n) {
var ret = [];
var i;
var len;
for(i = 0, len = str.length; i < len; i += n) {
ret.push(str.substr(i, n))
}
return ret
};
chunk("The quick brown fox jumps over the lazy dogs.", 5).join('$');
// "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs."
Keep it simple
var str = "123456789";
var parts = str.match(/.{1,3}/g);
var new_value = parts.join("-"); //returns 123-456-789
let s = 'The quick brown fox jumps over the lazy dogs.';
s.split('').reduce((a, e, i)=> a + e + (i % 5 === 4 ? '$' : ''), '');
Explain: split('') turns a string into an array. Now we want to turn the array back to one single string. Reduce is perfect in this scenario. Array's reduce function takes 3 parameters, first is the accumulator, second is the iterated element, and the third is the index. Since the array index is 0 based, to insert after 5th, we are looking at index i%5 === 4.
var str="ABCDEFGHIJKLMNOPQR";
function formatStr(str, n) {
var a = [], start=0;
while(start<str.length) {
a.push(str.slice(start, start+n));
start+=n;
}
console.log(a.join(" "));
}
formatStr(str,3);
function addItemEvery (str, item, every){
for(let i = 0; i < str.length; i++){
if(!(i % (every + 1))){
str = str.substring(0, i) + item + str.substring(i);
}
}
return str.substring(1);
}
Result:
> addItemEvery("The quick brown fox jumps over the lazy dogs.", '$', 5)
> "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs."
Here's one of the previous answers, but I wrapped it in a function, and I gave it an "offset" parameter instead of hard coding it.
// https://stackoverflow.com/a/2712896/3480193
addCharToStringEveryXSpots(str, char, offset) {
if ( ! char ) {
return str;
}
let regExPattern = new RegExp('(.{' + offset + '})', 'g');
return str.replace(regExPattern, '$1' + char);
};
//first parameter: the string to be divided
//second parameter: the character used to separate
//third parameter: the number of characters in each division
function separateStr(str, divider, n)
{
var ret=[];
for(let i=0; i<str.length; i=i+n)
{
ret.push(str.substr(i, n))
};
return ret.join(divider);
};
separateStr('123456789', '.', 3);
//Output: '123.456.789'
I did something similar to separate a friendCode
for a mobile app but using Array and reduce.
This will take a string, check every n
characters and add delimiter at that location.
/**
* A function to easily inject characters every 'n' spaces
* @param {string} friendCode The string we want to inject characters in
* @param {*} numDigits Determines the 'n' spaces we want to inject at
* @param {*} delimiter The character(s) we want to inject
*/
function formatFriendCode(friendCode, numDigits, delimiter) {
return Array.from(friendCode).reduce((accum, cur, idx) => {
return accum += (idx + 1) % numDigits === 0 ? cur + delimiter : cur;
}, '')
}
formatFriendCode("000011112222", 4, ' ')
// output "0000 1111 2222 "
formatFriendCode("The quick brown fox jumps over the lazy dogs.", 5, '$')
// output "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs.$"
本文标签: stringHow can I insert a character after every n characters in javascriptStack Overflow
版权声明:本文标题:string - How can I insert a character after every n characters in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736775718a1952326.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论