使用 JavaScript 分割单词,但会跳过“\”之前的一些单词

发布于 2024-12-06 08:07:14 字数 205 浏览 0 评论 0原文

我有一个字符串:

"a","b","c"

我可以将这些单词拆分为:

a
b
c

使用 Javascript,但是怎么样:

"a,","b\"","c\,\""

我如何得到:

a,
b"
c,"

I have a string:

"a","b","c"

and I can split those words to:

a
b
c

using Javascript, but how about:

"a,","b\"","c\,\""

How do I get:

a,
b"
c,"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

灼疼热情 2024-12-13 08:07:14

仍然不确定这是否是一根绳子?但如果它是...并且这是您想要操纵的唯一实例,您可以使用这种超级复杂的方式...

var a = '"a,","b\"","c\,\""';
var b = a.replace(/"/,'');
  //get rid of the first "
var c = b.lastIndexOf('"');
  //find the last "
var d = b.substring(0,c);
  //cut the string to remove the last "
var e = d.split('","');
  //split the string at the ","

for(var i="0"; i<e.length; i++){
    document.write(e[i] + '<br />');    
}

示例: http://jsfiddle.net/jasongennaro/ceVG7/1/

Still not sure if this is one string? But if it is... and this is the only instance of it that you want manipulated, you could use this super convoluted way....

var a = '"a,","b\"","c\,\""';
var b = a.replace(/"/,'');
  //get rid of the first "
var c = b.lastIndexOf('"');
  //find the last "
var d = b.substring(0,c);
  //cut the string to remove the last "
var e = d.split('","');
  //split the string at the ","

for(var i="0"; i<e.length; i++){
    document.write(e[i] + '<br />');    
}

Example: http://jsfiddle.net/jasongennaro/ceVG7/1/

淡写薰衣草的香 2024-12-13 08:07:14
  1. 按照原样拆分
  2. 在拆分后替换每个结果字符串中的任何 \(使用 replace()
  1. Split as you were
  2. Replace any \ in each resultant string, after the split (using replace())
素染倾城色 2024-12-13 08:07:14

您不能将“a”、“b”、“c”定义为一个字符串。如果你有一个字符串,则

replace()方法会搜索子字符串(或正则表达式)和字符串之间的匹配项,并用新的子字符串替换匹配的子字符串。

string.replace(regexp/substr,newstring)

split() 方法用于将字符串拆分为子字符串数组,并返回新数组。

string.split(separator, limit)

或者
var myString = "abc,efg";

var mySplitResult = myString.split(",");

mySplitResult[0] will be abc
mySplitResult[0] will be efg

You cannot define "a","b","c" as one string. If you have a string then,

The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring.

string.replace(regexp/substr,newstring)

The split() method is used to split a string into an array of substrings, and returns the new array.

string.split(separator, limit)

or
var myString = "abc,efg";

var mySplitResult = myString.split(",");

mySplitResult[0] will be abc
mySplitResult[0] will be efg
寒江雪… 2024-12-13 08:07:14

怎么样:

'"a,","b\"","c\,\""'.replace(/^"|"$/g,'').split(/"\s*,\s*"/).join('<br/>')

如果输出不是 HTML,则可以将

a,<br/>b"<br/>c,"

替换为 \n

What about this:

'"a,","b\"","c\,\""'.replace(/^"|"$/g,'').split(/"\s*,\s*"/).join('<br/>')

that gives:

a,<br/>b"<br/>c,"

<br/> can be replaced by \n if the output is not HTML

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文